Need Help With React Development?

Work with our skilled React developers to accelerate your project and boost its performance.

Hire Reactjs Developers

Support On Demand!

When using Typescript define the type of custom function. Here in below example, define function FilterFn and ensure the function uses TData for type checking.

import React, { useState } from "react";
import Fuse from 'fuse.js'; // Ensure you have imported Fuse
/**
 * FilterFunction for Tanstack Table incorporating fuse's fuzzy search
 */
export const fuseFilterFn = <TData extends RowData>(
  row: Row<TData>,
  columnId: string,
  filterValue: any,
  addMeta: (meta: FilterMeta) => void
): boolean => {
  const searchPattern = filterValue.toString();
  // Retrieve the value from the row based on the columnId
  const value = row.getValue(columnId) as string;
  // Initialize Fuse with the value
  const fuse = new Fuse([value]);
  // Perform the search
  const searchResults = fuse.search(searchPattern);
  if (searchResults.length > 0) {
    // If any search result is found, consider the row as a match
    addMeta({ searchResults }); // Optionally, add any metadata for the search results
   return true;
  }
  return false;
};

The type RowData should be imported from Tanstack Table’s core or should be defined if it’s a custom type.
Integrating with the Table

The fuseFilterFn is passed directly to the useReactTable’s configuration:

const table = useReactTable({
  data,
  columns,
  getCoreRowModel: getCoreRowModel(),
  getSortedRowModel: getSortedRowModel(),
  getPaginationRowModel: getPaginationRowModel(),
  getFilteredRowModel: getFilteredRowModel(),
  state: {
    sorting: sorting,
    globalFilter: filtering,
    columnFilters: columnFilters,
  },
  globalFilterFn: fuseFilterFn, // Correctly typed custom filter function
  onSortingChange: setSorting,
  onGlobalFilterChange: setFiltering,
});

Related Q&A