Blog>
Snippets

Adding Filtering Capability to React Table with TanStack

Explains how to enable filtering in a React Table component, utilizing the useFilters hook for custom filter types.
import React from 'react';
import { useTable, useFilters } from 'react-table';
// Define a default UI for filtering
cost DefaultColumnFilter = ({
 column: { filterValue, setFilter },
}) => (
 <input
   value={filterValue || ''}
   onChange={e => {
     setFilter(e.target.value || undefined); // Set undefined to remove the filter entirely
   }}
   placeholder={`Search...`}
 />
);
This code snippet creates a default filter UI using an input field. It utilizes the useFilters hook from the react-table library. The 'setFilter' function is used to apply a filter to the data.
const Table = ({ columns, data }) => {
 const defaultColumn = React.useMemo(
   () => ({
     // Let's set up our default Filter UI
     Filter: DefaultColumnFilter,
   }),
   []
 );
 
 const {
   getTableProps,
   getTableBodyProps,
   headerGroups,
   rows,
   prepareRow,
 } = useTable(
   { columns, data, defaultColumn },
   useFilters // Use the useFilters hook to add filtering capabilities
 );
 
 return (
   <table {...getTableProps()}>
     <thead>
       {headerGroups.map(headerGroup => (
         <tr {...headerGroup.getHeaderGroupProps()}>
           {headerGroup.headers.map(column => (
             <th
               {...column.getHeaderProps()}
             >
               {column.render('Header')}
               {/* Render the default Filter UI */}
               <div>{column.canFilter ? column.render('Filter') : null}</div>
             </th>
           ))}
         </tr>
       ))}
     </thead>
     <tbody {...getTableBodyProps()}>
       {rows.map(row => {
         prepareRow(row);
         return (
           <tr {...row.getRowProps()}>
             {row.cells.map(cell => {
               return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
             })}
           </tr>
         );
       })}
     </tbody>
   </table>
 );
}
This code implements a table component with filtering functionality. It initializes the useTable hook with the columns, data, and defaultColumn, which contains our DefaultColumnFilter. The UI for filtering is rendered within the header of each column that can be filtered.