Blog>
Snippets

Sorting and Filtering Data with TanStack Ranger

Provide examples of implementing sortable columns and filterable data in a React component using TanStack Ranger, including setting up sort and filter functions.
import { useTable, useSortBy, useFilters } from 'react-table';
import React from 'react';
Imports the necessary hooks from react-table and React.
const Table = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = useTable(
    {
      columns,
      data,
    },
    useFilters, // Using the useFilters hook to enable filtering
    useSortBy // Using the useSortBy hook to enable sorting
  );

  // Render the UI for your table
  return (
    // use getTableProps() to wire up the table element
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps(column.getSortByToggleProps())}>
                {column.render('Header')}
                <span>
                  {column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''}
                </span>
              </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>
  );
};
Defines a Table component using useTable, useFilters, and useSortBy hooks to handle the table logic.
const DefaultColumnFilter = ({
  column: { filterValue, preFilteredRows, setFilter },
}) => {
  const count = preFilteredRows.length;

  return (
    <input
      value={filterValue || ''}
      onChange={e => {
        setFilter(e.target.value || undefined); // Set undefined to remove the filter entirely
      }}
      placeholder={`Search ${count} records...`}
    />
  );
};
Defines a default filter UI component that can be used for filtering columns.
const columns = React.useMemo(
  () => [
    {
      Header: 'Name',
      accessor: 'name',
      Filter: DefaultColumnFilter, // Use the DefaultColumnFilter component above as the filter UI
    },
    {
      Header: 'Age',
      accessor: 'age',
      Filter: DefaultColumnFilter,
    }
    // Add more columns as needed
  ],
  []
);
Initializes the columns of the table, including setting up filter components.
const data = React.useMemo(() => [
    { name: 'Tania', age: 32 },
    { name: 'Kane', age: 43 },
    // Add more rows as needed
  ], []);
Defines sample data to populate the table.
<Table columns={columns} data={data} />
Renders the Table component with the specified columns and data.