React-Table: useSortBy
useSortBy
Sorting is perhaps the simplest hook to implement. It's really just a few lines of code to the DataTable component.
import React from "react";
import { useTable, useSortBy } from "react-table"; // highlight-line
const DataTable = (props) => {
// Memos
const data = React.useMemo(() => props.data, [props.data]);
const columns = React.useMemo(() => props.columns, [props.columns]);
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow
} = useTable(
{
columns,
data
},
useSortBy // highlight-line
);
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, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell) => {
return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
})}
</tr>
);
})}
</tbody>
</table>
);
};
export default DataTable;
That's really all there is to it. Click on a header and it will sort.
Default Sorting
It is possible to set a default sort on a specific column, just like it is possible to set a default filter on a column. Or both at the same time (in fact I recommend it). We will cover that in the next post on initialState.
Comments
Recent Work
Basalt
basalt.softwareFree desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.
BidBear
bidbear.ioBidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.