Implementing Custom Sorting Logic
Demonstrates how to implement a custom sorting function in React TanStack Table by comparing values of a specific column, accounting for both ascending and descending orders.
import { useSortBy, useTable } from 'react-table';
const Table = ({ columns, data }) => {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable(
{
columns,
data,
initialState: { sortBy: [{ id: 'your-column-id', desc: false }] },
sortTypes: {
// Custom sort function
customSort: (rowA, rowB, columnName, desc) => {
if (rowA.values[columnName] > rowB.values[columnName]) return desc ? -1 : 1;
if (rowA.values[columnName] < rowB.values[columnName]) return desc ? 1 : -1;
return 0;
}
}
},
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>
);
};
This code defines a component Table which accepts columns and data as props. It uses the useTable and useSortBy hooks from react-table. A custom sort function named 'customSort' is defined within the 'sortTypes' option of useTable hook, which checks the values of a specified column to determine the order. The sorting direction is toggled through the column headers, visual indicators for sorting direction are also displayed next to sorted column headers.