Implementing Multi-Column Sorting
Provide a code example showing how to enable and handle multi-column sorting in React TanStack Table for a more flexible data organization.
import { useReactTable, getSortedRowModel, SortingState } from '@tanstack/react-table';
Import necessary functions from '@tanstack/react-table'.
const [sorting, setSorting] = React.useState<SortingState>([]);
Define a state to manage sorting configuration. Initially, it's an empty array.
const table = useReactTable({
data,
columns,
state: { sorting, },
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
});
Initialize the table instance with sorting state and configure it to use the getSortedRowModel function for handling the sorted data model.
<thead>{table.getHeaderGroups().map(headerGroup => (
<tr key={headerGroup.id}>
{headerGroup.headers.map(header => (
<th key={header.id}>
{header.isPlaceholder ? null : (
<div onClick={() => header.column.getToggleSortingHandler()()}> // Enables click to sort
{flexRender(header.column.columnDef.header, header.getContext())}
{/* Display sorting direction arrows or indicators here */}
{header.column.getIsSorted() ? (header.column.getIsSorted() === 'desc' ? ' 🔽' : ' 🔼') : ''}
</div>
)}
</th>
))}
</tr>
))}</thead>
Render table header with sorting indicators. Clicking on the column header toggles its sorting state and updates the indicators accordingly.