Blog>
Snippets

Implementing Row Selection

Showcase the implementation of a row selection feature in TanStack Table using the useRowSelect hook, including checkbox selection.
import { useTable, useRowSelect } from '@tanstack/react-table';
Import the necessary hooks from TanStack Table.
const IndeterminateCheckbox = React.forwardRef(({ indeterminate, ...rest }, ref) => {
    const defaultRef = React.useRef();
    const resolvedRef = ref || defaultRef;

    React.useEffect(() => {
        resolvedRef.current.indeterminate = indeterminate;
    }, [resolvedRef, indeterminate]);

    return (
        <>
            <input type='checkbox' ref={resolvedRef} {...rest} />
        </>
    );
});
Define a component for the checkbox with support for the indeterminate state.
const tableInstance = useTable({ columns, data }, useRowSelect, hooks => {
    hooks.visibleColumns.push(columns => [
        // Let's make a column for selection
        {
            id: 'selection',
            // The header can use the table's getToggleAllRowsSelectedProps method
            // to render a checkbox
            Header: ({ getToggleAllRowSelectedProps }) => (
                <div>
                    <IndeterminateCheckbox {...getToggleAllRowSelectedProps()} />
                </div>
            ),
            // The cell can use the individual row's getToggleRowSelectedProps method
            // to the render a checkbox
            Cell: ({ row }) => (
                <div>
                    <IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />
                </div>
            )
        },
        ...columns
    ]);
});
Extend the table instance to include a new column for row selection, using the IndeterminateCheckbox component.
const { getTableProps, getTableBodyProps, headers, rows, prepareRow } = tableInstance;
Destructure the necessary properties from the table instance for rendering.
<table {...getTableProps()}>
    <thead>
        {headers.map(column => (
            <th {...column.getHeaderProps()}>{column.render('Header')}</th>
        ))}
    </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 selection column, leveraging the table and row properties provided by react-table.