Blog>
Snippets

Implementing Fuzzy Search with Fuse.js in React TanStack Table

Illustrate how to integrate fuzzy searching capabilities into the React TanStack Table's filtering mechanism using the Fuse.js library for more forgiving search results.
import Fuse from 'fuse.js';
Import Fuse.js library to use for fuzzy searching.
const fuseSearch = (rows, id, filterValue) => {
  const fuse = new Fuse(rows.map(row => row.values), {
    keys: [id],
    includeScore: true
  });
  const result = fuse.search(filterValue);
  return result.map(item => rows[item.refIndex]);
};
Define a custom search function using Fuse.js, mapping rows and filtering based on a column ID and filter value.
const columns = React.useMemo(
  () => [
    {
      Header: 'Name',
      accessor: 'name',
      filter: 'fuzzyText',
    },
    // Add other column definitions here
  ], []
);
Define column configurations for the table, marking specific columns to use the fuzzyText filter.
useReactTable({
  columns,
  data,
  filterTypes: React.useMemo(() => ({
    fuzzyText: fuseSearch
  }), []),
  globalFilter: 'fuzzyText'
});
Initialize the React Table with column and data configurations, specifying custom filter types and setting the global filter to use the fuzzyText filter.