Blog>
Snippets

Adding Controlled Filters in React TanStack Table

Explains how to create a controlled filtering system using the useFilters hook. Features examples on filtering table data based on user input.
import React, { useState } from 'react';
import { useTable, useFilters } from '@tanstack/react-table';
Import necessary hooks from React and TanStack Table.
function DefaultColumnFilter({
  column: { filterValue, setFilter },
}) {
  return (
    <input
      value={filterValue || ''}
      onChange={e => setFilter(e.target.value)}
      placeholder={`Search...`}
    />
  );
}
Defines a default column filter component that will be used for each column in the table.
const columns = React.useMemo(
  () => [
    {
      Header: 'Name',
      accessor: 'name',
      Filter: DefaultColumnFilter, // Custom filtering component for the 'Name' column
    },
    // Define other columns here
  ],
  []
);
Set up the columns for the table, each with potentially its own filter component. For this example, a default filter is used for all.
const Table = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = useTable(
    {
      columns,
      data,
    },
    useFilters // Using the useFilters hook to allow for column filtering
  );

  return (
    // Table structure
  );
};
Creates a table component that utilizes the useFilters hook for filtering based on column.
function App() {
  const data = React.useMemo(() => [{ name: 'John Doe' }, { name: 'Jane Doe' }], []);
  
  return <Table columns={columns} data={data} />;
}
Defines the App component where the table is rendered with predefined data and columns.