Custom Global Filter Function for React TanStack Table
Showcase coding a custom global filter function that searches across all table columns and integrates it with TanStack Table's useGlobalFilter hook.
import { useGlobalFilter, useReactTable } from '@tanstack/react-table';
Imports the useGlobalFilter hook from @tanstack/react-table which is required for implementing global filtering.
// Custom global filter function
const globalFilterFn = (rows, ids, query) => {
// Convert query to lowercase for case-insensitive comparison
const lowercasedQuery = query.toLowerCase();
// Filter rows where any cell contains the query string
return rows.filter(row => {
return ids.some(id => {
const rowValue = row.values[id];
return String(rowValue).toLowerCase().includes(lowercasedQuery);
});
});
};
Defines a custom global filter function that checks if any column's value in a row includes the search query. This function is case-insensitive.
// Use the custom global filter function in useReactTable
const tableInstance = useReactTable({
data: myData,
columns: myColumns,
state: { globalFilter: '' },
onGlobalFilterChange: setGlobalFilter,
globalFilterFn: globalFilterFn
});
Integrates the custom global filter function with useReactTable hook. This setup allows the table to use the provided globalFilterFn for filtering across all columns based on the globalFilter state.