Blog>
Snippets

Basic Column Visibility Toggle

Implement a basic toggle feature to show or hide columns in React TanStack Table using visibility state.
import { useReactTable } from '@tanstack/react-table';
Import useReactTable hook from TanStack Table library.
const columns = React.useMemo(() => [...], []);
Define your table columns. Replace [...] with your actual column definitions.
const data = React.useMemo(() => [...], []);
Define your table data. Replace [...] with your actual data array.
const [columnVisibility, setColumnVisibility] = React.useState({});
Set up state to manage the visibility of columns. Initially, all columns are visible.
const tableInstance = useReactTable({
  data,
  columns,
  state: { columnVisibility },
  onColumnVisibilityChange: setColumnVisibility
});
Initialize the table instance with data, columns, state for column visibility, and a method to update visibility state.
return (
  <div>
    {tableInstance.getHeaderGroups().map(headerGroup => (
      <div>
        {headerGroup.headers.map(header => (
          <button
            type="button"
            onClick={() =>
              setColumnVisibility(old => ({
                ...old,
                [header.id]: !old[header.id]
              }))
            }
          >
            {header.id}
          </button>
        ))}
      </div>
    ))}
    <table>
      {...}
    </table>
  </div>
);
Render the table with buttons to toggle the visibility of each column. Replace `{...}` with your table's body rendering logic.