Blog>
Snippets

Implementing Column Sorting Using useSortBy

Demonstrate adding sortable columns to a React TanStack Table using the useSortBy hook, including custom sort functions for complex data.
import React from 'react';
import { useTable, useSortBy } from '@tanstack/react-table';
import { useMemo } from 'react';
First, we import the necessary hooks from React and the TanStack Table library.
const data = useMemo(() => [
    { firstName: 'John', age: 30 },
    { firstName: 'Alice', age: 24 },
    // Add more data here
], []);
Define your table data using useMemo for performance optimization.
const columns = useMemo(() => [
    {
        Header: 'First Name',
        accessor: 'firstName',
    },
    {
        Header: 'Age',
        accessor: 'age',
        // Example of a custom sort function for the 'Age' column
        sortType: (rowA, rowB) => {
            return rowA.original.age - rowB.original.age;
        }
    }
    // Define more columns here
], []);
Define columns for the table. Include a custom sort function for complex data sorting, such as numerical values.
function Table({ columns, data }) {
    const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        rows,
        prepareRow,
    } = useTable({ columns, data }, useSortBy);
    
    return (
        <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>
    );
}
Implement the Table component. Utilize useTable and useSortBy for sorting functionality. This includes rendering sortable columns and displaying sort indicators.