Sorting Data Using Row Models
Provide an example of sorting table data alphabetically using row models in TanStack Table, including a toggle feature for ascending and descending order.
import { useReactTable, getCoreRowModel, getSortedRowModel } from '@tanstack/react-table';
Import necessary hooks and utilities from TanStack Table.
const table = useReactTable({
columns,
data,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel()
});
Initialize the table instance with columns and data, and configure the row models for core and sorted data.
const toggleSort = (columnId) => {
table.setSorting((old) => {
if (old.length === 0 || old[0].id !== columnId) {
// Not sorted or sorted by another column, start ascending sort
return [{ id: columnId, desc: false }];
}
if (!old[0].desc) {
// Currently ascending, switch to descending
return [{ id: columnId, desc: true }];
}
// Currently descending, remove sort
return [];
});
};
Function to toggle sorting order for a column. It starts with ascending, changes to descending on the next call, and removes sorting if called again.
return table.getRowModel().rows.map(row => (
// Render your table rows based on the sorted row model
));
Render the rows based on the sorted row model to present the data in either ascending or descending order, based on user's choice.