5

I have used the show property to show/hide columns in my table earlier and it has worked fine using react-table v7. However, recently I cannot get it to work any longer, since I've made a bunch of changes and my table is quite complex I'm not sure what caused it, possibly also an update of react-table itself (7.0.0-beta.12 to 7.0.0-rc.5).

Anyway, now I can't even get the most basic show example to work:

const columns = React.useMemo(
() => [
  {
    Header: "Info",
    columns: [
      {
        Header: "Age",
        accessor: "age",
        show: false
      },
      {
        Header: "Visits",
        accessor: "visits"
      }
    ]
  }
],
[]);

https://codesandbox.io/s/react-table-hide-column-2g3js

Why is the 'age' column showing?

Edit Digging into the changelog I now understand that column show/hide has indeed changed:

7.0.0-beta.28 Added the useColumnVisibility plugin as a core plugin along with several new instance and column-level methods to control column visibility Added the "column-hiding" example

However, I still have not figured out how to apply the useColumnVisibility hook to a column in a similar way to how show used to work. The "column-hiding" example shows how to do it with checkboxes but does not help in my case (afaik).

jola
  • 977
  • 2
  • 10
  • 31

2 Answers2

14

I had a similar issue as I was using show. Instead of setting show in the column, set the initialState.hiddenColumns, here you can convert your existing show into the initial hidden columns:

  useTable<T>(
    {
      columns,
      data,
      hiddenColumns: columns.filter(column => !column.show).map(column => column.id)
    },

I couldn't use that as my columns are loaded dynamically (so the initial state was set to some columns that didn't exist, and was just set to an empty array) so I used:

  React.useEffect(
    () => {
      setHiddenColumns(
        columns.filter(column => !column.show).map(column => column.id)
      );
    },
    [columns]
  );

where setHiddenColumns is provided by useTable:

const {
    headerGroups,
    rows,
    prepareRow,
    state,
    toggleRowSelected,
    toggleAllRowsSelected,
    setHiddenColumns
  } = useTable<T>(
    {
      columns,
      data,
      getRowId,
      ...

This means if I changed the column props it would be reflected in the table.

Joe
  • 6,773
  • 2
  • 47
  • 81
1

I also use setHiddenColumns to show/hide columns. However, instead returning Header, I use id. My code:

...
  setHiddenColumns,
  flatColumns,
  headerGroups,
  state: { pageIndex, pageSize },
} = useTable({
  columns,
  data,
  initialState: { pageIndex: 0 },
  manualPagination: true,
  pageCount: controlledPageCount,
},
  useSortBy,
  usePagination
);

React.useEffect(() => {
const hiddenColumns = flatColumns.filter((column: any) => !column.show).map((column: any)=> column.id);
setHiddenColumns(hiddenColumns); }, []);