Blog>
Snippets

Implementing Sorting in React Table with TanStack

Demonstrates how to add sorting functionality to a React Table using the useSortBy hook from TanStack.
import { useTable, useSortBy } from '@tanstack/react-table';
First, import the useTable and useSortBy hooks from TanStack.
const columns = React.useMemo(() => [
  // Define columns
  {
    Header: 'Name',
    accessor: 'name'
  },
  {
    Header: 'Age',
    accessor: 'age'
  }
], []);
Define the columns for the table including headers and accessors.
const data = React.useMemo(() => [
  // Example data
  { name: 'John', age: 28 },
  { name: 'Jane', age: 34 },
  { name: 'Jack', age: 45 }
], []);
Define the data to be displayed in the table.
const {
  getTableProps,
  getTableBodyProps,
  headerGroups,
  rows,
  prepareRow
} = useTable({ columns, data }, useSortBy);
Instantiate the table instance using useTable hook, passing in columns, data, and the useSortBy hook for sorting functionality.
return (
  <table {...getTableProps()}>
    <thead>
      {headerGroups.map(headerGroup => (
        <tr {...headerGroup.getHeaderGroupProps()}>
          {headerGroup.headers.map(column => (
            // Render the header
            <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 => {
              // Render the cell
              return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
            })}
          </tr>
        );
      })}
    </tbody>
  </table>
);
Render the table with sorting functionality. Use getSortByToggleProps to control the sorting state for each column. Display a sorting indicator based on the column's sorting state.