Blog>
Snippets

Applying Filters to Row Models

Explain how to apply filters to row models in TanStack Table, showcasing a simple text input filter to search through table data.
import { useTable, useGlobalFilter } from 'react-table';
Import the required hooks from TanStack Table (previously React Table).
const Table = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    setGlobalFilter, // the setGlobalFilter function is used to apply global filter
    state: { globalFilter },
  } = useTable({ columns, data }, useGlobalFilter);
  return (
    <div>
      {/* Filter input field */}
      <input
        value={globalFilter || ''}
        onChange={e => setGlobalFilter(e.target.value)}
        placeholder={'Search...'}
      />
      <table {...getTableProps()}>
        <thead>
          {/* Render the headers */}
        </thead>
        <tbody {...getTableBodyProps()}>
          {/* Render the rows */}
        </tbody>
      </table>
    </div>
  );
};
This code snippet demonstrates the creation of a table component using TanStack Table with global filtering applied. It includes an input field for the filter and uses the setGlobalFilter function to update the filter value.