Blog>
Snippets

Implementing Sorting in TanStack Table

Showcase how to enable and handle sorting functionality for columns in a TanStack Table component.
import { useTable, useSortBy } from 'react-table';
First, import useTable and useSortBy hooks from 'react-table' to enable sorting.
const columns = React.useMemo(() => [
    {
      Header: 'Name',
      accessor: 'name', // accessor is the 'key' in the data
    },
    {
      Header: 'Age',
      accessor: 'age',
    },
  // Add more columns here
], []);
Define the columns for your table, including header names and accessors that match the keys in your data.
const data = React.useMemo(() => [
    { name: 'John', age: 23 },
    { name: 'Mary', age: 34 },
    // Add more data here
], []);
Define the data to be displayed in your table. Each object in the array represents a row in your table.
const tableInstance = useTable({ columns, data }, useSortBy);
Create a table instance using useTable hook and enable sorting by passing useSortBy as a plugin hook.
const {
  getTableProps,
  getTableBodyProps,
  headerGroups,
  rows,
  prepareRow,
} = tableInstance;
Destructure methods and arrays provided by the table instance to handle table rendering.
<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>
Render the table with sorting functionality enabled. Use getSortByToggleProps method to enable sorting on a per-column basis. A click on the column header will toggle its sorting state and the sorting direction is indicated by an up or down arrow.