Blog>
Snippets

Implementing Column Sorting in React TanStack Table

Shows how to configure a column to be sortable by implementing a custom sorting function that compares the lengths of string values in a React TanStack Table.
import { useTable, useSortBy, Column } from '@tanstack/react-table';
import React from 'react';
Import necessary hooks and types from TanStack Table library.
const columns = [
  {
    accessorKey: 'name', // Accessor is the "key" in the data
    header: 'Name',
    sortingFn: 'basic',
  },
  {
    accessorFn: rowData => rowData.name.length,
    id: 'nameLength',
    header: 'Name Length',
    sortingFn: (rowA, rowB) => {
      // Custom sorting function to compare the lengths of names
      if (rowA.getValue() < rowB.getValue()) return -1;
      if (rowA.getValue() > rowB.getValue()) return 1;
      return 0;
    }
  }
];
Define columns for the table. The second column uses a custom accessor function returning the length of the 'name' field, and a custom sorting function comparing these lengths.
const DataTable = ({ data }) => {
  const tableInstance = useTable(
    {
      data,
      columns,
    },
    useSortBy
  );
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = tableInstance;

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps(column.getSortByToggleProps())}>{column.render('header')}</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>
  );
}
Implement the DataTable component using useTable and useSortBy hooks for rendering a table with sortable columns. This component generates a table element with sorted data.