Blog>
Snippets

Custom Filtering in TanStack Table

Explain how to add a custom filter UI to TanStack Table, enabling users to filter rows based on specific criteria.
import { useTable, useFilters } from '@tanstack/react-table';
First, import useFilters from TanStack Table alongside useTable to enable the filtering feature.
// Define a default UI for filtering
columns.forEach(column => {
  if (!column.Filter) {
    // Default UI Component for filtering
    column.Filter = ({ column: { setFilter } }) => (
      <input
        onChange={e => setFilter(e.target.value || undefined)}
        placeholder={`Search ${column.id}`}
      />
    );
  }
});
Define a default UI component for column filtering. Each column gets an input box if no other filter UI is specified.
function Table({ columns, data }) {
  const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow, } = useTable(
    {
      columns,
      data,
    },
    useFilters // Use the useFilters hook
  );

  return (
    // Render the table UI including the filter UI per column as defined
  );
}
Set up the TanStack Table instance with useFilters. Render the table UI, incorporating the default or custom filter UIs for each column.