Blog>
Snippets

Enabling Column Filtering in TanStack Table

Provide an example of adding filter functionality to table columns in TanStack Table to help users narrow down the data displayed.
import { useTable, useFilters } from 'react-table';
Importing necessary hooks from react-table.
function DefaultColumnFilter({
 column: { filterValue, preFilteredRows, setFilter },
}) {
 return (
 <input
 value={filterValue || ''}
 onChange={e => {
 setFilter(e.target.value || undefined);
 }}
 placeholder={`Search ${preFilteredRows.length} records...`}
 />
 );
}
Defines a default column filter component.
const columns = React.useMemo(
 () => [
 {
 Header: 'Name',
 accessor: 'name',
 Filter: DefaultColumnFilter,
 filter: 'includes',
 },
 // Add other column definitions here
 ],
 []
);
Setup columns with a filter UI component defined. This example adds a filter to the 'Name' column.
const tableInstance = useTable({ columns, data }, useFilters);
Initialize useTable hook with filtering capabilities.
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = tableInstance;
Destructure table instance to get table properties and methods.