Blog>
Snippets

Adding Sorting Functionality to Columns

Show how to enable sorting features on table columns using the TanStack Table sorting hooks and rendering sortable column headers.
import { useTable, useSortBy } from '@tanstack/react-table';
Import the necessary hooks from TanStack Table.
const columns = React.useMemo(() => [
    {
        Header: 'Name',
        accessor: 'name',
    },
    {
        Header: 'Age',
        accessor: 'age',
    },
    // Add more column definitions here
], []);
Define the columns for your table, including header names and accessors for the data. These columns will be made sortable.
const data = React.useMemo(() => [
    { name: 'Alice', age: 30 },
    { name: 'Bob', age: 26 },
    // Add more data here
], []);
Define the data that will populate the table. Each object in the array corresponds to a row in the table.
const tableInstance = useTable({
    columns,
    data,
}, useSortBy);
Create a table instance using useTable hook, passing in the columns and data. The useSortBy hook is also applied to enable sorting functionality.
const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
} = tableInstance;
Destructure the table instance to get properties and methods for rendering the table in your component.
{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>
))}
Use the getSortByToggleProps method from the column to make each header clickable for sorting. The presence of sorting arrows (ascending or descending) depends on the sorting state of each column.