Blog>
Snippets

Integrating Global Filtering

Provide an example of adding a global filter to a TanStack Table using the useGlobalFilter hook, detailing how to create a filter input and bind it to the table's data filtering mechanism.
import { useGlobalFilter, useTable } from '@tanstack/react-table';
First, import the necessary hooks from the TanStack Table library.
const [filter, setFilter] = React.useState('');
Create a state to manage the filter input value.
<input value={filter} onChange={e => setFilter(e.target.value)} placeholder="Search..." />
Render an input element for the global filtering of the table's data. Updating the state on each change.
const tableInstance = useTable({ columns, data }, useGlobalFilter);
Initialize the table instance, including the useGlobalFilter hook to enable global filtering functionality.
tableInstance.setGlobalFilter(filter);
Bind the filter state to the table's global filter, ensuring that the table's data is filtered based on the input's value.