Blog>
Snippets

Implementing Column Sorting in TanStack Table

Demonstrate how to add sortable columns in TanStack Table using the useSortBy hook.
import { useReactTable, createColumnHelper, getCoreRowModel, useSortBy } from '@tanstack/react-table';
Import necessary functions and hooks from @tanstack/react-table.
const columnHelper = createColumnHelper<TypeOfData>();
Create a column helper to define columns easily.
const columns = [
  columnHelper.accessor('id', {
    header: 'ID',
    cell: ({ getValue }) => getValue(),
    // Enable sorting for this column
    sortingFn: 'auto',
  }),
  // Add more columns as needed
];
Define the columns for the table, including enabling sorting on the 'id' column using the 'sortingFn' property.
const table = useReactTable({
  data: yourDataArray,
  columns,
  getCoreRowModel: getCoreRowModel(),
  // Enable sorting functionality for the table
  useSortBy,
});
Initialize the table instance with the useReactTable hook, enabling sorting with the useSortBy hook.
<table>
  <thead>
    {table.getHeaderGroups().map(headerGroup => (
      <tr>
        {headerGroup.headers.map(header => (
          <th
            {...header.column.getSortByToggleProps()}
          >
            {header.isPlaceholder ? null : header.renderHeader()}
            {/* Display a sorting indicator */}
            {header.column.getCanSort() ? (
              header.column.getIsSorted() ? (
                header.column.getIsSortedDesc() ? ' 🔽' : ' 🔼'
              ) : (
                ' ⬍'
              )
            ) : null}
          </th>
        ))}
      </tr>
    ))}
  </thead>
  <tbody>{/* Render rows here */}</tbody>
</table>
Render the table with sortable columns. Clicking on the table headers will toggle sorting for that column. Sorting indicators (up/down arrows) represent the current sorting state.