Blog>
Snippets

Implementing Custom Sorting in TanStack Table

Showcase how to implement custom sorting functionality in TanStack Table, allowing users to sort data based on specific criteria.
import { useTable } from 'react-table';
Import the useTable hook from react-table which is needed to create a table instance.
const data = React.useMemo(() => [...], []);
Define your table's data. The data should be in the form of an array of objects where each object represents a row in the table.
const columns = React.useMemo(() => [
 { 
    Header: 'Custom Sort Column',
    accessor: 'customSortColumn',
    // Define a custom sort function for this column
    sortType: (rowA, rowB) => {
        // Custom sort logic. For example, comparing string lengths.
        return rowA.values.customSortColumn.length - rowB.values.customSortColumn.length;
    }
 }], []);
Define your table columns. This includes setting up a custom sort function for a specific column using the sortType property. In this example, rows are sorted by the length of the string in the 'customSortColumn'.
const tableInstance = useTable({ columns, data });
Create a table instance by calling useTable hook with your columns and data.
const { getTableProps, getTableBodyProps, headers, rows, prepareRow } = tableInstance;
Destructure necessary properties and methods from the table instance to be used in rendering your HTML table.
<table {...getTableProps()}>
    <thead>
        {headers.map(column => (
            <th {...column.getHeaderProps()}>{column.render('Header')}</th>
        ))}
    </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 HTML table using the properties and methods from the table instance. This includes setting up the table, thead, and tbody tags, along with mapping through the headers and rows to generate the content dynamically.