Reputation: 24488
Using Tanstack table ver 8, how do I dynamically hide specific columns?
I have column defined
{
header: "Case Number",
accessorKey: "caseNumber",
visible: false, // use this value
},
I am trying to use the "visible: false" to hide the column when the table is rendered.
There is a columnVisibility setting, but I cant seem to get it working.
Upvotes: 0
Views: 1794
Reputation: 74
The following solutions didn't work for me.
That's what I did :
useState,
useEffect
} from 'react';
export function useMediaQuery(query: string) {
const [matches, setMatches] = useState(false);
useEffect(() => {
const media = window.matchMedia(query);
if (media.matches !== matches) {
setMatches(media.matches);
}
const listener = () => {
setMatches(media.matches);
};
media.addEventListener('change', listener);
return () => media.removeEventListener('change', listener);
}, [matches, query]);
return matches;
}
Then, in data-table.tsx :
const detectMD = useMediaQuery('(min-width: 768px)');
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
useEffect(() => {
setColumnVisibility((prev) => ({
...prev,
username: detectMD,
status: detectMD,
}));
}, [detectMD]);
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
onColumnFiltersChange: setColumnFilters,
getFilteredRowModel: getFilteredRowModel(),
onColumnVisibilityChange: setColumnVisibility,
state: {
sorting,
columnFilters,
columnVisibility,
},
});
I added the useEffect + the hook + my columns ids with boolean in the setColumnVisibility.
Sorry for the form, the UI is really a pain to edit.
Upvotes: 0
Reputation: 24488
Using Ver 8:
Function GetInVisibleColumn() takes an array of finalColumnDef and filters out the columns that have the visible property set to false. It then creates a new object (removedColumn) where the keys are the accessorKey properties of the invisible columns, and the values are set to false.
const columns = useMemo(
....
{
header: "Case Number",
accessorKey: "caseNumber",
visible: false,
},
then
const tableInstance: any = useReactTable({
...
initialState: {
columnVisibility: GetInVisibleColumn(finalColumnDef),
function GetInVisibleColumn(finalColumnDef: any) {
let inVisibleColumns = finalColumnDef.filter(
(col: { visible: boolean }) => col.visible === false
);
const removedColumn = {} as Record<string, boolean>;
for (const item of inVisibleColumns) {
removedColumn[item.accessorKey] = false;
}
return removedColumn;
}
Upvotes: 1