Creating a Custom Filter UI for TanStack Table
Illustrate how to create a custom filter UI using TanStack Table’s useFilters hook, enabling users to filter table data through input fields or dropdowns.
// FilterForm.js
import React from 'react';
export const Filter = ({ column }) => (
<div style={{ marginTop: '5px' }}>
<input
value={column.filterValue || ''}
onChange={e => column.setFilter(e.target.value)}
placeholder={`Search ${column.id}`}
/>
</div>
);
This component creates an individual filter input for a column in the table. It utilizes the `setFilter` method from a column instance to apply the filter value.
// TableComponent.js
import React from 'react';
import { useTable, useFilters } from 'react-table';
import { Filter } from './FilterForm';
export const TableComponent = ({ columns, data }) => {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({ columns, data }, useFilters);
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>
{column.render('Header')}
<Filter column={column} />
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map(row => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
))}
</tr>
);
})}
</tbody>
</table>
);
}
This is the main table component. It initializes the table using the useTable hook with columns and data props, while integrating the useFilters hook for filtering functionality. Each column header renders a Filter component to enable filtering inputs.