Blog>
Snippets

Basic Sorting Implementation in React TanStack Table

Show how to implement basic ascending and descending sorting in React TanStack Table using the useSortBy hook.
import { useTable, useSortBy } from '@tanstack/table';
First, import the necessary hooks from TanStack Table.
const columns = [
    { key: 'id', header: 'ID', sortable: true },
    { key: 'name', header: 'Name', sortable: true },
    { key: 'email', header: 'Email', sortable: true },
];
Define the columns for your table, making sure to indicate which ones are sortable.
const data = [{ id: 1, name: 'John', email: 'john@example.com' }, /* more rows... */ ];
Prepare the data for your table, typically this would come from state or props.
const tableInstance = useTable({ columns, data }, useSortBy);
Create a table instance using useTable and passing useSortBy as a plugin hook to enable sorting.
const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
} = tableInstance;
Destructure utility functions and variables from the table instance for rendering.
<table {...getTableProps()}>
    <thead>
    {headerGroups.map(headerGroup => (
        <tr {...headerGroup.getHeaderGroupProps()}>
        {headerGroup.headers.map(column => (
            <th {...column.getHeaderProps(column.getSortByToggleProps())}>{column.render('header')}
            {column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''}
            </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 enabled. Clicking on the column headers toggles sorting for that column.