Implementing Sorting in Table Headers
Demonstrates how to add sortable functionality to table headers using the useSortBy hook from the TanStack Table library.
import { useTable, useSortBy } from 'react-table';
First, import useTable and useSortBy hooks from react-table to enable table functionalities and sorting.
function Table({ columns, data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({ columns, data }, useSortBy);
// Followed by the Table markup
}
Wrap your table component logic with useTable and useSortBy to enable sorting by clicking on column headers.
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
// Add sorting indicators and functionality to headers
<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>
);
Render headers with sorting functionality. Users can click on a column header to sort by that column.