Enabling Controlled Sorting in React TanStack Table
Showcases how to implement controlled sorting using the useSortBy hook with React TanStack Table. Includes handling ascending and descending sorting logic.
import { useTable, useSortBy } from 'react-table';
import React from 'react';
Imports necessary hooks from react-table and React.
const data = React.useMemo(() => [...], []);
Initializes the data for the table, memoized to avoid unnecessary recalculations.
const columns = React.useMemo(() => [
{ Header: 'Column 1', accessor: 'col1' },
{ Header: 'Column 2', accessor: 'col2' },
// Add more columns as needed
], []);
Defines the columns for the table, including header names and data accessors, memoized to avoid unnecessary recalculations.
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({ columns, data }, useSortBy);
Initializes the table instance with sorting functionalities using useSortBy hook.
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
// This will render the header cell and add sorting props
<th {...column.getHeaderProps(column.getSortByToggleProps())}>
{column.render('Header')}
{/* Add a sorting direction indicator */}
<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>
);
Renders the table, headers with sorting capabilities, and the data rows. Headers will show a sorting indicator based on the column's current sorting state.