Dev Helpers
← Back

Sortable numeric table

Import and render <SortableNumericTable /> in a React project.

Open this example in the interactive library

Live preview

Source code

// components/SortableNumericTable.tsx

import { useState } from "react";

export default function SortableNumericTable({
  rows = [
    { name: "Design", value: 12 },
    { name: "Build", value: 18 },
  ],
}: { rows?: { name: string; value: number }[] } = {}) {
  const [asc, set] = useState(true);
  return (
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th aria-sort={asc ? "ascending" : "descending"}>
            <button onClick={() => set(!asc)}>Hours</button>
          </th>
        </tr>
      </thead>
      <tbody>
        {[...rows]
          .sort((a, b) => (asc ? a.value - b.value : b.value - a.value))
          .map((r) => (
            <tr key={r.name}>
              <th>{r.name}</th>
              <td>{r.value}</td>
            </tr>
          ))}
      </tbody>
    </table>
  );
}