I have a table that contains list of tld's which can be filtered via a search box or buttons for specific categories. The buttons filter based on a list of tld's while the search box should fuzzy match the tld's.
const columns = useMemo(
() => [
{
Header: 'TLD',
accessor: 'tld',
filter: multiFilter,
Cell: (props) => {
const onSale = props.row.original.sale
return (
<div>
.{props.value} {onSale ? <span className="font-bold text-purple m-left-1">Sale</span> : null}
</div>
)
},
},
Button filtering
<button autoFocus className="py-1 px-4 text-sm focus:bg-blue focus:rounded-full" onClick={() => setFilter('tld', undefined)}>All</button>
<button className="py-1 px-4 text-sm focus:bg-blue focus:rounded-full" onClick={() => setFilter('tld', sale)}>Sale</button>
Search box filtering
<input id="tld-search-box" value={searchFilterInput} onChange={handleSearchFilterChange} placeholder={'Enter a domain extension here'} className="border border-gray-300 p-2 w-[640px] rounded-full" />
For the buttons I had to make a custom filter method
function multiFilter(rows, columnIds, filterValue) {
return filterValue.length === 0
? rows
: rows.filter((row) =>
filterValue.includes(String(row.original[columnIds])),
);
}
And this is the search filter method which ends up using setFilter so it flows through the custom filter method eventually also
const handleSearchFilterChange = (e) => {
const value = e.target.value || undefined
const trimmedValue = value ? value.replace(/^\./g, '') : undefined
setFilter('tld', trimmedValue)
setSearchFilterInput(value)
}
The problem I have is since they both use the custom filter method in the end, the search box filtering is an exact match per the includes method filterValue.includes(String(row.original[columnIds])),. I want the search box to match anything that contains the value entered however and I am not sure how to do this since they both act on the column. Any advice would be greatly appreciated.
I suppose global filtering could also solve this issue but I ended up finding that the two search types were of different JS types. The buttons were type object while the search bar was string so this solved the issue:
function multiFilter(rows, columnIds, filterValue) {
return filterValue.length === 0 ? rows : rows.filter((row) => {
let match = String(row.original[columnIds])
return typeof filterValue === 'object'
? filterValue.includes(match) // Check to see if match is in array
: match.includes(filterValue) // do sub string match for strings
})
}