Blog>
Snippets

Filtering Data in TanStack Table

Demonstrate how to add a filter UI to TanStack Table columns, including debounced input for efficient filtering of large datasets.
import { useAsyncDebounce } from 'react-table';
// Define a default UI for filtering
function GlobalFilter({
  preGlobalFilteredRows,
  globalFilter,
  setGlobalFilter,
}) {
  const count = preGlobalFilteredRows.length;
  const [value, setValue] = React.useState(globalFilter);
  const onChange = useAsyncDebounce(value => {
    setGlobalFilter(value || undefined);
  }, 200);

  return (
    <span>
      Search: {' '}
      <input
        value={value || ""}
        onChange={e => {
          setValue(e.target.value);
          onChange(e.target.value);
        }}
        placeholder={`${count} records...`}
        style={{
          fontSize: '1.1rem',
          border: '0',
        }}
      />
    </span>
  );
}
This code creates a functional component called GlobalFilter using React. It employs useAsyncDebounce from react-table for efficient querying by delaying the filter operation until 200ms after the user stops typing. It's designed to work as a global filter for a TanStack Table, allowing users to filter through all rows across all columns.
function Table({ columns, data }) {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    state,
    preGlobalFilteredRows,
    setGlobalFilter,
  } = useTable(
    {
      columns,
      data,
    },
    useFilters, // useFilters plugin hook for column filtering
    useGlobalFilter // useGlobalFilter plugin hook for global filtering
  );

  return (
    // Table markup goes here
    <div>
      <GlobalFilter
        preGlobalFilteredRows={preGlobalFilteredRows}
        globalFilter={state.globalFilter}
        setGlobalFilter={setGlobalFilter}
      />
      {/* Rest of table rendering */}
    </div>
  );
}
This code snippet showcases the basic setup for a table component using TanStack Table with global filtering capability enabled. It integrates the previously defined GlobalFilter component into the table, receiving and managing the global filter state through the useTable hook. The hooks useFilters and useGlobalFilter are activated to provide column and global filtering functionalities, respectively.