Change globalFilterFn at runtime? #6111
Replies: 1 comment 1 reply
-
|
The issue is that changing The cleanest fix is to not swap function names at all. Instead, write a single custom filter function that reads the current mode from a ref or state: const [caseSensitive, setCaseSensitive] = useState(false)
const globalFilterFn: FilterFn<any> = useCallback((row, columnId, filterValue) => {
const cellValue = String(row.getValue(columnId) ?? '')
const search = String(filterValue)
if (caseSensitive) {
return cellValue.includes(search)
}
return cellValue.toLowerCase().includes(search.toLowerCase())
}, [caseSensitive])
const table = useReactTable({
data,
columns,
state: {
globalFilter,
// ...
},
globalFilterFn,
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
})But this alone still won't trigger a re-filter. The trick is to force the filtered model to recompute when the mode changes. The simplest way: toggle the globalFilter value to trigger a recomputation: function toggleCaseSensitivity() {
setCaseSensitive((prev) => !prev)
// Force re-filter by "touching" the filter value
setGlobalFilter((prev) => prev)
}If that doesn't work (since it's the same reference), bump it slightly: function toggleCaseSensitivity() {
setCaseSensitive((prev) => !prev)
// Force re-filter
setGlobalFilter((prev) => prev + ' ')
// Then trim it back on next tick
requestAnimationFrame(() => setGlobalFilter((prev) => prev.trim()))
}Or, a cleaner approach — encode the sensitivity mode into the filter value itself: const [caseSensitive, setCaseSensitive] = useState(false)
const [searchText, setSearchText] = useState('')
// Combine mode + text into the globalFilter value
const globalFilter = useMemo(
() => ({ text: searchText, caseSensitive }),
[searchText, caseSensitive]
)
const globalFilterFn: FilterFn<any> = (row, columnId, filterValue) => {
const { text, caseSensitive: cs } = filterValue as { text: string; caseSensitive: boolean }
const cellValue = String(row.getValue(columnId) ?? '')
return cs
? cellValue.includes(text)
: cellValue.toLowerCase().includes(text.toLowerCase())
}This way, changing |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I made a global filter input to my table with the option for the filter to be case sensitive or not:
Internally, this toggles a state from
includeStringtoincludeStringSensitivethat is then passed touseReactTable.However this doesn't seems to trigger any rerender. I had to make a wrap my data in a use memo and a dummy id number that I then increment for the change to be picked up.
Is this use case not intended by the library? Is there a better way to do this?
Thanks for help. 👋
Beta Was this translation helpful? Give feedback.
All reactions