Replies: 3 comments
|
Yes, you can do this by initializing // Build initial visibility state with all columns hidden
const initialVisibility = Object.fromEntries(
columns.map((col) => [col.id ?? col.accessorKey, false])
)
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({
...initialVisibility,
// Only these columns are visible:
name: true,
email: true,
})
const table = useReactTable({
data,
columns,
state: { columnVisibility },
onColumnVisibilityChange: setColumnVisibility,
getCoreRowModel: getCoreRowModel(),
})If you want this to be truly dynamic (e.g., columns are defined elsewhere and you always want hidden-by-default), you can create a helper: function hiddenByDefault(
columns: ColumnDef<any>[],
visible: string[]
): VisibilityState {
const state: VisibilityState = {}
for (const col of columns) {
const id = (col as any).id ?? (col as any).accessorKey
if (id) {
state[id] = visible.includes(id)
}
}
return state
}
// Usage:
const [columnVisibility, setColumnVisibility] = useState(
hiddenByDefault(columns, ['name', 'email'])
)You don't need to override |
|
Because Depending on whether you want a clean declarative pattern or a direct API override, here are the two ways to achieve hidden-by-default behavior: Approach 1: Helper Initialization (Declarative & Safe)The standard and most robust approach in v8 is to populate import { useMemo } from 'react';
import { ColumnDef, useReactTable, getCoreRowModel } from '@tanstack/react-table';
function useHiddenByDefaultVisibility<TData>(
columns: ColumnDef<TData>[],
activeVisibleColumnIds: string[]
) {
return useMemo(() => {
const visibility: Record<string, boolean> = {};
// Recursively traverse column definitions to extract all leaf column IDs
const extractIds = (cols: ColumnDef<TData>[]) => {
for (const col of cols) {
if ('columns' in col && Array.isArray(col.columns)) {
extractIds(col.columns);
} else {
const id = col.id ?? (col as any).accessorKey;
if (id) visibility[id] = false;
}
}
};
extractIds(columns);
// Explicitly enable only the requested columns
for (const id of activeVisibleColumnIds) {
visibility[id] = true;
}
return visibility;
}, [columns, activeVisibleColumnIds]);
}Usage:const columnVisibility = useHiddenByDefaultVisibility(columns, ['name', 'status']);
const table = useReactTable({
data,
columns,
state: {
columnVisibility,
},
onColumnVisibilityChange: setColumnVisibility,
getCoreRowModel: getCoreRowModel(),
});Approach 2: Overriding
|
|
Hi @danolekh! Regarding Column visibility - hidden by default in TanStack Table:
Let us know if you have specific code snippet details! |
Uh oh!
There was an error while loading. Please reload this page.
This is the api that defines whether column is visible.
I want to make all the columns hidden by default, meaning it will be visible only there is an attribute with value 'true' in provided columnVisibility object. Is there a way to override this api?
All reactions