Filtering Rows in TanStack Table
Provide an example of adding a text input filter to filter rows in a TanStack Table based on a certain column's value.
import React, { useMemo, useState } from 'react';
import { useTable, useFilters } from 'react-table';
Import necessary React hooks and useFilters from react-table.
function DefaultColumnFilter({
column: { filterValue, preFilteredRows, setFilter },
}) {
const count = preFilteredRows.length;
return (
<input
value={filterValue || ''}
onChange={e => {
setFilter(e.target.value || undefined); // Set filter to undefined to remove the filter
}}
placeholder={`Search ${count} records...`}
/>
);
}
Defines a default column filter component that provides an input for filtering rows based on column value.
const columns = useMemo(
() => [
{
Header: 'Name',
accessor: 'name',
Filter: DefaultColumnFilter, // Use the default column filter in the Name column
},
// Other column definitions...
],
[]
);
Defines columns for the table, including a 'Name' column that uses the DefaultColumnFilter for filtering.
const data = useMemo(() => [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 27 },
// More rows...
], []);
Defines dummy data for the table.
const tableInstance = useTable({ columns, data }, useFilters); // Apply the useFilters hook
Initializes the table instance with columns and data, applying the useFilters hook for filtering functionality.
return (
<table>
{/* Table mark-up with tableInstance properties */}
</table>
);
Renders the table with the applied filters.