Blog>
Snippets

Integrating Data Filtering Feature

Explain how to implement a data filtering feature on a TanStack Table using the useFilters hook for column-based filtering.
import { useTable, useFilters } from '@tanstack/react-table';
First, we import the necessary hooks from the '@tanstack/react-table' package.
function DefaultColumnFilter({
  column: { filterValue, setFilter },
}) {
  return (
    <input
      value={filterValue || ''}
      onChange={e => setFilter(e.target.value)}
    />
  );
}
Define a default column filter component. This component renders an input field and uses the setFilter function provided by the column object to update the filter value.
const columns = React.useMemo(
  () => [
    {
      Header: 'ID',
      accessor: 'id',
      Filter: DefaultColumnFilter,
      filter: 'includes',
    },
    // Add more column definitions here
  ],
  []
);
Define column configurations using React.useMemo. We specify a 'Filter' component for the columns we want to be filterable, and the 'filter' prop defines the filter logic 'includes' for string inclusion.
const tableInstance = useTable({ columns, data, defaultColumn: { Filter: DefaultColumnFilter } }, useFilters);
Initialize the table instance using useTable hook with our columns and data. We also provide a default Column Filter to be used by all columns unless overridden and we include the useFilters hook to enable filtering logic on the table.
const { getTableProps, headerGroups, rows, prepareRow } = tableInstance;
Destructure the necessary methods and properties from the table instance to manage the table's layout and behavior.
{/* Usage within the component's return statement. Example for rendering the table */}
<table {...getTableProps()}>
  <thead>
    {headerGroups.map(headerGroup => (
      <tr {...headerGroup.getHeaderGroupProps()}>
        {headerGroup.headers.map(column => (
          <th {...column.getHeaderProps()}>
            {column.render('Header')}
            {/* Render the column filter UI */}
            <div>{column.canFilter ? column.render('Filter') : null}</div>
          </th>
        ))}
      </tr>
    ))}
  </thead>
  <tbody>
    {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 structure with headers and cells, including rendered filter components for applicable columns. This provides a basic UI for filtering data on a column basis.