Blog>
Snippets

Integrating Global Filtering with TanStack Table

Illustrates the process of adding a global filter to a TanStack Table, allowing users to filter data across all columns using a single input.
import { useGlobalFilter, useTable } from 'react-table';
import React, { useMemo, useState } from 'react';
Import necessary hooks from react-table and React.
const GlobalFilter = ({ globalFilter, setGlobalFilter }) => {
  return (
    <span>
      Search: {' '}
      <input
        value={globalFilter || ''}
        onChange={e => setGlobalFilter(e.target.value)}
        placeholder="Type to search..."
      />
    </span>
  );
};
Defines a global filter component that can be used to filter across all columns.
const TableComponent = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    state,
    setGlobalFilter,
  } = useTable(
    {
      columns,
      data,
    },
    useGlobalFilter
  );
Initialize the useTable hook with useGlobalFilter for global filtering capability.
const { globalFilter } = state;

  return (
    <>
      <GlobalFilter
        globalFilter={globalFilter}
        setGlobalFilter={setGlobalFilter}
      />
      <table {...getTableProps()}>
        <thead>
          {/* Render the header rows here */}
        </thead>
        <tbody {...getTableBodyProps()}>
          {/* Render the body rows here */}
        </tbody>
      </table>
    </>
  );
}
Renders the table component with a global filter input. The global filter state is managed within the TableComponent, enabling a single input to filter across all columns.