Applying Filters to Table Data
Shows how to add filtering functionality to a table, allowing users to filter results based on specific criteria using the useFilters hook.
import React from 'react';
import { useTable, useFilters } from 'react-table';
First step is importing necessary hooks from react-table.
const DefaultColumnFilter = ({
column: { filterValue, setFilter },
}) => (
<input
value={filterValue || ''}
onChange={e => setFilter(e.target.value || undefined)}
placeholder={`Search...`}
/>
);
Defining a default filter component to be used in each column for filtering.
const Table = ({ columns, data }) => {
const defaultColumn = React.useMemo(
() => ({
Filter: DefaultColumnFilter
}),
[]
);
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow
} = useTable(
{
columns,
data,
defaultColumn
},
useFilters
);
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>
{column.render('Header')}
<div>{column.canFilter ? column.render('Filter') : null}</div>
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
})}
</tr>
);
})}
</tbody>
</table>
);
};
Implementing the table component with column filtering using the useFilters hook from react-table. The DefaultColumnFilter component is specified as the default filtering UI for every column.
export default Table;
Exporting the Table component.