Using Custom Filter Components in React TanStack Table
Provides an example of creating a custom filter component using a dropdown menu to filter rows in a React TanStack Table based on a column's enum values.
import { createColumnHelper, useReactTable } from '@tanstack/react-table';
import React, { useMemo } from 'react';
Import necessary hooks and React.
const StatusFilter = ({ column: { setFilter } }) => (
<select
onChange={e => setFilter(e.target.value || undefined)}
style={{ width: '100%' }}
>
<option value="">All</option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select>
);
Define a custom filter component 'StatusFilter' for filtering by status.
const columnHelper = createColumnHelper();
Initialize the column helper.
const columns = useMemo(() => [
columnHelper.accessor('status', {
header: 'Status',
cell: info => info.getValue(),
filterFn: 'equals',
Filter: StatusFilter
}),
// Define other columns here
], []);
Define columns using useMemo, including one with the custom filter component.
const data = useMemo(() => [
// Your data here
], []);
Define the table data.
function Table() {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
});
return (
// Render the table using table instance
);
}
Create a React component 'Table' containing the table, utilizing the useReactTable hook.
export default Table;
Export the 'Table' component for use in your app.