How to hide columns using TanStack Ver 8

110 views Asked by At

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.

1

There are 1 answers

0
Ravi Ram On

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;
}