Blog>
Snippets

Implementing Sorting in React TanStack Table

Configure sortable columns in React TanStack Table using the built-in useSortBy hook to enable ascending and descending sorting.
import { useTable, useSortBy } from 'react-table';

// Table component
function Table({ columns, data }) {
  // Use the state and functions returned from useTable and useSortBy to build your UI
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = useTable(
    {
      columns,
      data,
    },
    useSortBy // Adding useSortBy hook to enable sorting
  );

  // Render the UI for your table
  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              // Add sorting props to column headers
              <th {...column.getHeaderProps(column.getSortByToggleProps())}>
                {column.render('Header')}
                {/* Sort direction indicator */}
                <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>
  );
}
This code snippet demonstrates how to integrate sorting functionality into a table using the TanStack Table (previously known as React Table). It utilizes the `useSortBy` hook to make columns sortable. When a column's header is clicked, the rows will be sorted based on that column. The sort direction is indicated by arrows.