Implementing a Faceted Search UI
Provide an example of creating a user interface for faceted search with React TanStack Table, including checkboxes for users to select faceted values.
import { useTable } from '@tanstack/react-table';
import Checkbox from '@mui/material/Checkbox';
// Component to render the faceted search checkboxes
function FacetCheckbox({ column, value, onChange }) {
return (
<label>
<Checkbox
checked={column.getFacetedUniqueValues().has(value)}
onChange={onChange}
/>
{value} ({column.getFacetedValueCount()[value]})
</label>
);
}
Defines a FacetCheckbox component using Material UI's Checkbox component. It takes a column from TanStack Table, a value for the facet, and an onChange handler as props. Displays the facet value, and how many times it appears using column.getFacetedValueCount method.
function FacetedSearchTable({ data, columns }) {
const tableInstance = useTable({
data,
columns,
state: {
columnFilters: [],
},
});
const { getTableProps, getTableBodyProps, rows, prepareRow, allColumns } = tableInstance;
return (
<div>
{allColumns.map(column => (
<div key={column.id}>
{column.render('Header')}
{column.canFilter &&
column.getFacetedUniqueValues().map(value => (
<FacetCheckbox
key={value}
column={column}
value={value}
onChange={(e) => column.setFilterValue(e.target.checked ? value : undefined)}
/>
))}
</div>
))}
<table {...getTableProps()}>
<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>
</div>
);
}
Creates a FacetedSearchTable component using TanStack Table. The component renders a set of FacetCheckbox components for each column that supports filtering. Each checkbox controls the filtering for its specific value. The table displays rows that match the active faceted filters.