Blog>
Snippets

Implementing Basic Sorting in TanStack Table

Demonstrate how to enable basic sorting functionality on a column in TanStack Table, including asc/desc toggles.
import { useTable, useSortBy } from 'react-table';
Import the useTable and useSortBy hooks from react-table.
// Define columns for the table
This is a placeholder comment for defining columns.
const columns = React.useMemo(
    () => [
        {
            Header: 'Column 1',
            accessor: 'col1',
            // This column uses the `useSortBy` hook to enable sorting.
            disableSortBy: false
        },
        {
            Header: 'Column 2',
            accessor: 'col2',
            disableSortBy: false
        }
        // Add more columns as needed
    ],
    []
);
Define the table columns and enable sorting on them by not setting `disableSortBy` or setting it to false.
// Define data for the table
This is a placeholder comment for defining data.
const data = React.useMemo(
    () => [
        {
            col1: 'Hello',
            col2: 'World'
        },
        {
            col1: 'react-table',
            col2: 'rocks'
        }
        // Add more data as needed
    ],
    []
);
Define mock data for the table for demonstration.
// Use the useTable and useSortBy hooks to initialize the table instance.
This is a placeholder comment for initializing the table instance.
const tableInstance = useTable({ columns, data }, useSortBy);
Initialize the table instance with sorting functionality by passing the useSortBy hook.
const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
} = tableInstance;
Destructure the table instance to get the necessary properties and methods.
// Table structure goes here
This is a placeholder comment for the table structure, including how to render headers and rows with sorting control.