日本語

How to Choose Visible Columns with Checkboxes in React and TanStack Table

​​React​TanStack Table,TypeScript

In TanStack Table v9, register columnVisibilityFeature, and pass column.getToggleVisibilityHandler() to a checkbox for each column. Unchecking the checkbox removes that column from the table. This works when an admin list table has too many columns and overflows horizontally, and you want users to pick only the columns they need (show or hide columns).

In a test environment with a five-column table, I recorded how the visibility state (columnVisibility) and the table headers and cells changed each time I operated the checkboxes.

Note

The test environment was Ubuntu 24.04 and Node.js 22.23.4. I used @tanstack/react-table 9.3.1 (and @tanstack/table-core 9.3.1, which it uses internally), react / react-dom 19.3.1, @types/react / @types/react-dom 19.3.0, typescript 7.0.2, and esbuild 0.28.2. I type-checked the .tsx with tsc, built it for production with esbuild, and ran it in Chromium from Playwright 1.63.0. I did not wrap the app in StrictMode.

I did not test the TanStack Table v8 API, the approach the official guide recommends of holding state in an external atom (TanStack Store), saving the chosen columns in the browser, column groups (two-level headers), combining with column pinning or reordering, or screen reader announcements.

In v9, register columnVisibilityFeature before using it

Install @tanstack/react-table. The installation guide says it works with React 18 and later.

text
npm install @tanstack/react-table

In v9, you create the table with useTable and register the features you use with tableFeatures(). Column visibility is provided by columnVisibilityFeature. The column visibility guide says that adding it to features makes the related APIs available.

When I created a table without registering any features, such as with tableFeatures({}), and called column.getIsVisible(), the type check failed.

text
nofeature/src/NoFeature.tsx(16,44): error TS2339: Property 'getIsVisible' does not exist on type 'Column_Core<{}, Cat, unknown>'.
nofeature/src/NoFeature.tsx(16,77): error TS2339: Property 'getToggleVisibilityHandler' does not exist on type 'Column_Core<{}, Cat, unknown>'.

Define each column with a name to show next to its checkbox

The table shows five columns: name, age, weight, fur color, and memo. I used three rows of data.

ts
export type Cat = { name: string; age: number; weight: number; color: string; memo: string };

export const cats: Cat[] = [
  { name: 'たま', age: 3, weight: 4.2, color: '茶トラ', memo: '窓辺が好き' },
  { name: 'ミケ', age: 5, weight: 3.8, color: '三毛', memo: '人見知り' },
  { name: 'クロ', age: 8, weight: 4.6, color: '黒', memo: '夜に元気' },
];

Each checkbox needs a column name next to it. The guide notes that a column's header can be a string, JSX, or a function, and that some headers need header context to render, which hidden columns may not have. It recommends using a lookup table keyed by column ID. Here I made such a table and used the same names for the headers.

ts
import { columnVisibilityFeature, createColumnHelper, tableFeatures } from '@tanstack/react-table';
import type { Cat } from './cats';

// Register the column visibility feature
export const features = tableFeatures({ columnVisibilityFeature });

// Names shown next to the checkboxes (also used as headers)
export const columnLabels: Record<string, string> = {
  name: '名前',
  age: '年齢',
  weight: '体重(kg)',
  color: '毛の色',
  memo: 'ひとこと',
};

const columnHelper = createColumnHelper<typeof features, Cat>();

export const columns = columnHelper.columns([
  // Make the name column impossible to hide
  columnHelper.accessor('name', { header: columnLabels.name, enableHiding: false }),
  columnHelper.accessor('age', { header: columnLabels.age }),
  columnHelper.accessor('weight', { header: columnLabels.weight }),
  columnHelper.accessor('color', { header: columnLabels.color }),
  columnHelper.accessor('memo', { header: columnLabels.memo }),
]);

I added enableHiding: false to the "name" column. So that you can always tell which cat a row belongs to, this is the only column that cannot be hidden.

The checkboxes and the table component

I kept the visibility state with useState and passed it to useTable as state.columnVisibility and onColumnVisibilityChange. The guide says this v8-style approach still works, but for v9 it recommends passing an external atom (a TanStack Store state container) through atoms. This article uses useState, which makes the state easier to inspect.

tsx
import { useState } from 'react';
import { useTable, type ColumnVisibilityState } from '@tanstack/react-table';
import { cats } from './cats';
import { columnLabels, columns, features } from './columns';

// A table where checkboxes choose which columns to show
export function CatTable() {
  // Hide the "memo" column at first
  const [columnVisibility, setColumnVisibility] = useState<ColumnVisibilityState>({
    memo: false,
  });

  const table = useTable({
    features,
    columns,
    data: cats,
    state: { columnVisibility },
    onColumnVisibilityChange: setColumnVisibility,
  });

  const allVisible = table.getIsAllColumnsVisible();
  // Decide the intermediate state of "all" using only the columns that can be hidden
  const someVisible = table
    .getAllLeafColumns()
    .some((column) => column.getCanHide() && column.getIsVisible());

  return (
    <>
      <fieldset>
        <legend>表示する列</legend>
        <label>
          <input
            type="checkbox"
            checked={allVisible}
            ref={(el) => {
              if (el) el.indeterminate = someVisible && !allVisible;
            }}
            onChange={table.getToggleAllColumnsVisibilityHandler()}
          />
          すべて
        </label>
        {table.getAllLeafColumns().map((column) => (
          <label key={column.id}>
            <input
              type="checkbox"
              checked={column.getIsVisible()}
              disabled={!column.getCanHide()}
              onChange={column.getToggleVisibilityHandler()}
            />
            {columnLabels[column.id] ?? column.id}
          </label>
        ))}
      </fieldset>

      <table>
        <thead>
          {table.getHeaderGroups().map((headerGroup) => (
            <tr key={headerGroup.id}>
              {headerGroup.headers.map((header) => (
                <th key={header.id}>
                  <table.FlexRender header={header} />
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody>
          {table.getRowModel().rows.map((row) => (
            <tr key={row.id}>
              {row.getVisibleCells().map((cell) => (
                <td key={cell.id}>
                  <table.FlexRender cell={cell} />
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
      <pre id="state">{JSON.stringify(columnVisibility)}</pre>
    </>
  );
}

The checkbox list must include hidden columns too, so I use table.getAllLeafColumns(). The functions I used are listed below.

Function Usage
column.getIsVisible() Whether the column is visible. Passed to the checkbox's checked
column.getCanHide() Whether the column can be hidden. When false, the checkbox is disabled
column.getToggleVisibilityHandler() Returns a function to pass to the checkbox's onChange. Checked or unchecked maps directly to shown or hidden
table.getIsAllColumnsVisible() Whether all columns are visible
table.getToggleAllColumnsVisibilityHandler() Returns a function to pass to the "all" checkbox's onChange

The <pre id="state"> element is only there so I could see the contents of columnVisibility during testing.

Unchecking a column puts false under its ID

At first, the "memo" column was hidden, as the {"memo":false} passed to useState specifies. I then unchecked the "weight (kg)" checkbox and checked it again.

text
最初の表示
  columnVisibility: {"memo":false}
  見出し(4個): 名前 | 年齢 | 体重(kg) | 毛の色
  1行目(4個): たま | 3 | 4.2 | 茶トラ
----「体重(kg)」のチェックを外した
  columnVisibility: {"memo":false,"weight":false}
  見出し(3個): 名前 | 年齢 | 毛の色
  1行目(3個): たま | 3 | 茶トラ
----「体重(kg)」に、もう一度チェックを入れた
  columnVisibility: {"memo":false,"weight":true}
  見出し(4個): 名前 | 年齢 | 体重(kg) | 毛の色

Unchecking added "weight":false, and the weight column disappeared from both the headers and the cells. Checking it again did not remove the weight key; it set the value to true. According to the guide, a column is hidden only when its ID is present with the value false. Columns whose IDs are absent are shown. So for the initial state, it is enough to set false only for the columns you want hidden.

Pressing the Space key while a checkbox was focused toggled it the same way as clicking.

Five checkbox clicks. The weight and fur color checkboxes are unchecked, "all" shows every column, a second "all" leaves only the name column, and then the age checkbox is checked. The columnVisibility contents appear in the box below
How the table columns and columnVisibility change over five checkbox clicks

The click counter in the top right, the cursor graphic, and the pink rings were added by the recording script for display. Each time the table columns changed, the script drew a pink frame around the table and set the columnVisibility box below to a pink background. The counter in the top right turns pink only at the moment of a click.

The "all" checkbox keeps columns that cannot be hidden

Here is the record of clicking the "all" checkbox twice. Before the first click, the "memo" column was hidden, and "all" showed the intermediate state explained later.

text
----「すべて」をクリックした
  columnVisibility: {"name":true,"age":true,"weight":true,"color":true,"memo":true}
  見出し(5個): 名前 | 年齢 | 体重(kg) | 毛の色 | ひとこと
----「すべて」をもう一度クリックした
  columnVisibility: {"name":true,"age":false,"weight":false,"color":false,"memo":false}
  見出し(1個): 名前

The first click showed every column. The second left only the "name" column, the one marked enableHiding: false. In both cases, every column ID has a value. In the package code I checked, when hiding, the new state sets true for the columns that cannot be hidden and false for the rest. The "name" checkbox was disabled, and clicking it anyway did not change the state.

When some but not all columns are visible, the "all" checkbox shows an intermediate state (indeterminate), neither checked nor empty. As described in MDN's checkbox documentation, indeterminate cannot be set as an HTML attribute; you set the indeterminate property from JavaScript. So I set it on the input element received through ref.

I did not use table.getIsSomeColumnsVisible() to decide the intermediate state. That function returns true when at least one column is visible. In testing, it still returned true after I used "all" to leave only the name column, because the name column, which cannot be hidden, is visible. Instead, I checked only the columns where getCanHide() is true to see whether any of them were visible. With this, only the name column left shows an empty "all" checkbox, and checking "age" from there shows the intermediate state.

Render cells with getVisibleCells()

If you use row.getAllCells() instead of row.getVisibleCells() when rendering the table body, cells for hidden columns are rendered too. I changed only the cell function and unchecked the weight (kg) checkbox.

text
----「体重(kg)」のチェックを外した
  columnVisibility: {"memo":false,"weight":false}
  見出し(3個): 名前 | 年齢 | 毛の色
  1行目(5個): たま | 3 | 4.2 | 茶トラ | 窓辺が好き
A table rendered with getAllCells(). There are three headers, name, age, and fur color, but each row has five cells including weight and memo. The weight value appears under the fur color header
Rendering row cells with getAllCells() misaligns headers and cells

The headers dropped to three, but the cells remained five, including the hidden "memo" cell. Weight numbers appeared under the "fur color" header, and the columns no longer lined up. The guide also states that getAllCells() and getAllLeafColumns() ignore visibility, and that when rendering a table you should use getVisibleCells() and getVisibleLeafColumns(). getHeaderGroups() for the headers already reflects visibility.

Point

Build the checkbox list from all columns with getAllLeafColumns(), and build the table headers and cells from visible columns only, using getHeaderGroups() and getVisibleCells(). In this article's table, this split kept the checkboxes and the table columns in agreement.

​Posted by 86