React-Table: useSortBy

Contents

useSortBy

Sorting is perhaps the simplest hook to implement. It’s really just a few lines of code to the DataTable component.

/components/DataTable.js
import React from "react";
import { useTable, useSortBy } from "react-table";
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  );

  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.

Edit ncoughlin/react-table_useSortBy

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.