Using Row Selection in TanStack Table
Illustrate the implementation of row selection in TanStack Table, allowing users to select one or multiple table rows.
import { useTable, useRowSelect } from '@tanstack/react-table';
First, import the necessary hooks from Tanstack Table, including useRowSelect for row selection functionality.
const table = useTable({
columns,
data
},
useRowSelect,
hooks => {
hooks.visibleColumns.push(columns => [
// Let's make a column for selection
{
id: 'selection',
header: ({ getToggleAllRowsSelectedProps }) => (
<input type='checkbox' {...getToggleAllRowsSelectedProps()} />
),
cell: ({ row }) => (
<input type='checkbox' {...row.getToggleRowSelectedProps()} />
)
},
...columns
]);
});
Define the table instance with useTable hook, including configurations for columns and data. useRowSelect is used as a plugin hook to activate row selection. A new column for selection checkboxes is added using hooks.visibleColumns.
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = table;
Destructure the required properties and methods from the table instance for rendering.
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map(row => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
})}
</tr>
);
})}
</tbody>
</table>
Render the table with the ability to select rows. The header for selection checkboxes is rendered in the header, and each row has its own checkbox for selection.