Skip to content
Thrum

Data table

A table you hand columns and rows: the headings sort, rows can be selected, long lists split into pages, and a menu hides columns. It needs no table library. For a table you write by hand, with no sorting, use the table parts it is built on.

Install

npx shadcn@latest add https://thrumui.dev/r/data-table.json

Adds components/ui/data-table.tsx. Nothing else in your project changes.

import { sortRows } from "@/components/ui/data-table";

Automatically installs icons arrow-down, arrow-up, chevrons-up-down and columns from the icon set.

Data shape

Type
type DataTableValue = string | number | null; // a date is an ISO string or milliseconds
type DataTableRow = { id: string; [key: string]: DataTableValue };
type SortRule = { key: string; direction: "asc" | "desc" };
Sample
const accounts: DataTableRow[] = [
  { id: "a1", customer: "Acme", plan: "Team", seats: 24, mrr: 480, renews: "2027-03-01" },
  { id: "a2", customer: "Northwind", plan: "Business", seats: 60, mrr: 1920, renews: null },
  { id: "a3", customer: "Globex", plan: "Starter", seats: 3, mrr: 36, renews: "2027-01-12" },
];

Props

PropTypeDefaultDescription
columnsreadonly DataTableColumn[]RequiredThe columns in order: key, header, type (text, number or date), format, sortable, hideable and className.
rowsreadonly DataTableRow[]RequiredThe rows. Each needs a unique id. A missing value is null and prints as a dash.
captionstringRequiredWhat the table holds, shown above it. It names the table and its scrolling frame.
sortreadonly SortRule[]–The sort, when the parent holds it. The first rule sorts; the next ones break ties.
defaultSortreadonly SortRule[]Default []The sort at first, when the table holds it itself.
onSortChange(sort: SortRule[]) => void–Called with the new sort when a heading is pressed.
selectablebooleanDefault falseAdd a checkbox to each row and one in the header for every row of the page.
selectedIdsreadonly string[]–The selected ids, when the parent holds them.
defaultSelectedIdsreadonly string[]Default []The ids selected at first, when the table holds them itself.
onSelectedIdsChange(ids: string[]) => void–Called with every selected id, in row order, when the selection changes.
pagenumber–The current page, counted from 1, when the parent holds it.
defaultPagenumberDefault 1The page shown at first, when the table holds it itself.
onPageChange(page: number) => void–Called with the new page.
pageSizenumber–Rows on a page, when the parent holds it. Infinity shows every row and no pagination.
defaultPageSizenumberDefault 10Rows on a page at first, when the table holds it itself.
onPageSizeChange(pageSize: number) => void–Called with the new page size from the Rows per page select.
pageSizeOptionsreadonly number[]–The choices of a Rows per page select under the table. Leave it out for no select.
columnMenubooleanDefault falseShow a Columns menu that hides and shows the hideable columns. The last visible column cannot be hidden.
hiddenColumnsreadonly string[]–The keys of the hidden columns, when the parent holds them.
defaultHiddenColumnsreadonly string[]Default []The keys hidden at first, when the table holds them itself.
onHiddenColumnsChange(keys: string[]) => void–Called with every hidden key when the column menu changes.
loadingbooleanDefault falseUp to five placeholder rows replace the body, and the table carries aria-busy.
emptyLabelstringDefault "No data"Shown across the body when there are no rows.
density"compact" | "normal"Default "normal"compact rows are 32 pixels tall, normal rows 40.
stripedbooleanDefault falseShade every second row.
stickyHeaderbooleanDefault falseKeep the header row in view while the body scrolls. Give the frame a height with containerClassName.
containerClassNamestring–Classes for the scrolling frame, such as max-h-96.
localestringDefault "en-US"The locale that prints numbers and dates. Dates print in UTC unless a column's format sets timeZone.
soundbooleanDefault truePlay a click when the sort or the page changes and a pair of clicks when a row is selected or cleared, if the visitor has sound on.
classNamestring–Extra classes for the root, merged last.
sortRows(), nextSort(), formatCell()functions–More exports: the stable sort the table uses, the sort after a heading press, and a cell's printed text.

Motion and sound

Motion

  • A heading, a row and the page buttons shade over 150 ms under the pointer.
  • The column menu fades and grows from 96% over 150 ms; the checkbox ticks fade in over 150 ms.
  • Loading rows carry a slow shimmer while loading is set.
  • Reduced motion: shades and the menu change at once, and the shimmer stands still.

Sound

  • A click when a heading changes the sort, and when another page is picked.
  • A rising pair of clicks when a row is selected and a falling pair when it is cleared, for one row or the whole page.
  • A soft tone when the column menu opens and closes, and a pair of clicks when a column is hidden or shown.

Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works

Accessibility

  • It is a native table named by its caption. Sortable headings are buttons inside the header cells; the first sort key's heading carries aria-sort, and the others say their place in words.
  • The header checkbox is named Select all rows on this page and turns to a dash when some of the page is selected. Each row's checkbox is named after the row's first cell.
  • A polite line above the table says how many rows are selected, and the pagination reads the new page aloud.
  • A selected row is shaded, carries aria-selected, and its checkbox is ticked, so selection does not rest on colour.
  • Loading rows are hidden from screen readers and the table carries aria-busy. The empty state is a row that spans every column.
  • The frame is a panel surface: under a glass material its tint keeps text at 4.5 to 1. The column menu is a floating surface.
KeysAction
TabMove through the column menu, the frame, the sortable headings, the checkboxes and the page buttons.
Enter / SpaceOn a heading: sort by that column, ascending, then descending, then unsorted.
Shift + EnterOn a heading: add the column as the next sort key, or step it, and keep the others.
SpaceOn a checkbox: select or clear the row, or every row of the page from the header.
↑ / ↓ / EscIn the column menu: move between columns, close the menu. Enter or Space hides or shows a column.

Source

components/ui/data-table.tsx
"use client";

import { useState } from "react";

import { cn } from "@/lib/utils";
import { play } from "@/lib/thrum-sound";
import { buttonClass } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuLabel, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Pagination } from "@/components/ui/pagination";
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow, type TableDensity } from "@/components/ui/table";
import { ArrowDownIcon } from "@/components/icons/arrow-down";
import { ArrowUpIcon } from "@/components/icons/arrow-up";
import { ColumnsIcon } from "@/components/icons/columns";
import { ChevronsUpDownIcon } from "@/components/icons/chevrons-up-down";

/** A cell value. Dates are ISO strings or milliseconds since 1970. Missing is `null`. */
export type DataTableValue = string | number | null;

/** One row: a unique `id` and one value per column key. */
export type DataTableRow = { id: string; [key: string]: DataTableValue };

export type DataTableColumn = {
  /** The key of the value in each row. */
  key: string;
  /** The column heading. */
  header: string;
  /** How values compare and print. `number` and `date` columns align to the end. */
  type?: "text" | "number" | "date";
  /** `Intl.NumberFormatOptions` for a number column, `Intl.DateTimeFormatOptions` for a date column. Dates print in UTC unless `timeZone` is set. */
  format?: Intl.NumberFormatOptions | Intl.DateTimeFormatOptions;
  /** The heading sorts the rows. */
  sortable?: boolean;
  /** The column is listed in the column menu and can be hidden. */
  hideable?: boolean;
  /** Classes for the column's cells: a width, a weight. */
  className?: string;
};

export type SortDirection = "asc" | "desc";
/** One sort key. A list of them sorts by the first, then the second, and so on. */
export type SortRule = { key: string; direction: SortDirection };

const COLLATOR = new Intl.Collator("en-US", { numeric: true, sensitivity: "base" });

function sortable(value: DataTableValue, type: DataTableColumn["type"]): number | string | null {
  if (value === null || value === "") return null;
  if (type === "number") return typeof value === "number" ? (Number.isFinite(value) ? value : null) : Number.isFinite(Number(value)) ? Number(value) : null;
  if (type === "date") {
    const time = typeof value === "number" ? value : Date.parse(value);
    return Number.isFinite(time) ? time : null;
  }
  return String(value);
}

/**
 * The rows in the order of `sort`: by the first rule, then the next for ties, and so on. Rows that tie on every rule
 * keep their order (the sort is stable), and a missing value goes last in either direction. The input is not changed.
 */
export function sortRows<Row extends DataTableRow>(rows: readonly Row[], sort: readonly SortRule[], columns: readonly Pick<DataTableColumn, "key" | "type">[]): Row[] {
  const rules = sort
    .map((rule) => ({ ...rule, type: columns.find((column) => column.key === rule.key)?.type ?? "text" }))
    .filter((rule) => columns.some((column) => column.key === rule.key));
  if (rules.length === 0) return [...rows];
  const keyed = rows.map((row, index) => ({ row, index, keys: rules.map((rule) => sortable(row[rule.key] ?? null, rule.type)) }));
  keyed.sort((a, b) => {
    for (let i = 0; i < rules.length; i++) {
      const x = a.keys[i];
      const y = b.keys[i];
      if (x === y) continue;
      if (x === null) return 1;
      if (y === null) return -1;
      const order = typeof x === "number" && typeof y === "number" ? x - y : COLLATOR.compare(String(x), String(y));
      if (order !== 0) return rules[i].direction === "asc" ? order : -order;
    }
    return a.index - b.index;
  });
  return keyed.map((entry) => entry.row);
}

/**
 * The sort after a press on the heading of `key`. Each press steps that column through ascending, descending and
 * unsorted. Without `multi` the column becomes the only sort key; with it (Shift held) the other keys stay.
 */
export function nextSort(sort: readonly SortRule[], key: string, multi = false): SortRule[] {
  const current = sort.find((rule) => rule.key === key);
  const next: SortRule | null = !current ? { key, direction: "asc" } : current.direction === "asc" ? { key, direction: "desc" } : null;
  if (!multi) return next ? [next] : [];
  if (!current) return [...sort, next!];
  return next ? sort.map((rule) => (rule.key === key ? next : rule)) : sort.filter((rule) => rule.key !== key);
}

const formatters = new Map<string, Intl.NumberFormat | Intl.DateTimeFormat>();

/** A cell's text: numbers and dates through `Intl`, a missing value as a dash. */
export function formatCell(value: DataTableValue, column: Pick<DataTableColumn, "type" | "format">, locale = "en-US"): string {
  const key = sortable(value, column.type);
  if (key === null) return "–";
  if (column.type !== "number" && column.type !== "date") return String(key);
  const id = `${column.type}|${locale}|${JSON.stringify(column.format ?? {})}`;
  let formatter = formatters.get(id);
  if (!formatter) {
    formatter =
      column.type === "number"
        ? new Intl.NumberFormat(locale, column.format as Intl.NumberFormatOptions)
        : new Intl.DateTimeFormat(locale, { timeZone: "UTC", ...(column.format as Intl.DateTimeFormatOptions) });
    formatters.set(id, formatter);
  }
  return formatter.format(key as number);
}

export type DataTableProps = {
  /** The columns, in order. */
  columns: readonly DataTableColumn[];
  /** The rows. Each needs a unique `id`. */
  rows: readonly DataTableRow[];
  /** What the table holds, shown above it. It names the table. */
  caption: string;
  /** The sort, when the parent holds it. Use with `onSortChange`. */
  sort?: readonly SortRule[];
  /** The sort at first, when the table holds it itself. */
  defaultSort?: readonly SortRule[];
  /** Called with the new sort when a heading is pressed. */
  onSortChange?: (sort: SortRule[]) => void;
  /** Add a checkbox to every row and one in the header for the rows of the page. */
  selectable?: boolean;
  /** The ids of the selected rows, when the parent holds them. Use with `onSelectedIdsChange`. */
  selectedIds?: readonly string[];
  /** The ids selected at first, when the table holds them itself. */
  defaultSelectedIds?: readonly string[];
  /** Called with every selected id when the selection changes. */
  onSelectedIdsChange?: (ids: string[]) => void;
  /** The current page, counted from 1, when the parent holds it. Use with `onPageChange`. */
  page?: number;
  /** The page shown at first, when the table holds it itself. */
  defaultPage?: number;
  /** Called with the new page. */
  onPageChange?: (page: number) => void;
  /** Rows on a page, when the parent holds it. `Infinity` shows every row and no pagination. */
  pageSize?: number;
  /** Rows on a page at first, when the table holds it itself. */
  defaultPageSize?: number;
  /** Called with the new page size from the "Rows per page" select. */
  onPageSizeChange?: (pageSize: number) => void;
  /** The choices of a "Rows per page" select under the table. Leave it out for no select. */
  pageSizeOptions?: readonly number[];
  /** Show a "Columns" menu that hides and shows the `hideable` columns. */
  columnMenu?: boolean;
  /** The keys of the hidden columns, when the parent holds them. Use with `onHiddenColumnsChange`. */
  hiddenColumns?: readonly string[];
  /** The keys hidden at first, when the table holds them itself. */
  defaultHiddenColumns?: readonly string[];
  /** Called with every hidden key when the column menu changes. */
  onHiddenColumnsChange?: (keys: string[]) => void;
  /** Rows are on their way: placeholder rows replace the body and the table is marked busy. */
  loading?: boolean;
  /** Shown in the body when there are no rows. */
  emptyLabel?: string;
  /** `compact` rows are 32 pixels tall, `normal` rows 40. */
  density?: TableDensity;
  /** Shade every second row. */
  striped?: boolean;
  /** Keep the header in view while the body scrolls. Give the frame a height with `containerClassName`. */
  stickyHeader?: boolean;
  /** Classes for the table's scrolling frame, such as `max-h-96`. */
  containerClassName?: string;
  /** The locale that prints numbers and dates and compares text. */
  locale?: string;
  /** Play a click when the sort changes and a pair of clicks when a row is selected or cleared, if the visitor has sound on. */
  sound?: boolean;
  /** Classes for the root, merged last. */
  className?: string;
};

const ARIA_SORT = { asc: "ascending", desc: "descending" } as const;
const NUMERIC = (column: DataTableColumn) => column.type === "number" || column.type === "date";

/**
 * A table driven by `columns` and `rows`: headings that sort (Shift adds a second key), rows that can be selected,
 * pages, a menu that hides columns, loading and empty states. It is built on the `table` parts and needs no table library.
 */
export function DataTable({
  columns,
  rows,
  caption,
  sort: sortProp,
  defaultSort = [],
  onSortChange,
  selectable = false,
  selectedIds,
  defaultSelectedIds = [],
  onSelectedIdsChange,
  page: pageProp,
  defaultPage = 1,
  onPageChange,
  pageSize: pageSizeProp,
  defaultPageSize = 10,
  onPageSizeChange,
  pageSizeOptions,
  columnMenu = false,
  hiddenColumns,
  defaultHiddenColumns = [],
  onHiddenColumnsChange,
  loading = false,
  emptyLabel = "No data",
  density = "normal",
  striped = false,
  stickyHeader = false,
  containerClassName,
  locale = "en-US",
  sound = true,
  className,
}: DataTableProps) {
  const [innerSort, setInnerSort] = useState<readonly SortRule[]>(defaultSort);
  const [innerSelected, setInnerSelected] = useState<readonly string[]>(defaultSelectedIds);
  const [innerPage, setInnerPage] = useState(defaultPage);
  const [innerSize, setInnerSize] = useState(defaultPageSize);
  const [innerHidden, setInnerHidden] = useState<readonly string[]>(defaultHiddenColumns);

  const sort = sortProp ?? innerSort;
  const selected = new Set(selectedIds ?? innerSelected);
  const hidden = new Set(hiddenColumns ?? innerHidden);
  const size = Math.max(1, pageSizeProp ?? innerSize);
  const visible = columns.filter((column) => !hidden.has(column.key));
  const sorted = sortRows(rows, sort, columns);
  const pageCount = Number.isFinite(size) ? Math.max(1, Math.ceil(sorted.length / size)) : 1;
  const page = Math.min(pageCount, Math.max(1, Math.floor(pageProp ?? innerPage) || 1));
  const shown = Number.isFinite(size) ? sorted.slice((page - 1) * size, page * size) : sorted;

  const setSort = (next: SortRule[]) => {
    setInnerSort(next);
    onSortChange?.(next);
    if (sound) play("select");
  };
  const setSelected = (next: Set<string>) => {
    const ids = rows.filter((row) => next.has(row.id)).map((row) => row.id);
    setInnerSelected(ids);
    onSelectedIdsChange?.(ids);
  };
  const setPage = (next: number) => {
    setInnerPage(next);
    onPageChange?.(next);
  };

  const pageIds = shown.map((row) => row.id);
  const onPage = pageIds.filter((id) => selected.has(id)).length;
  const label = (row: DataTableRow) => formatCell(row[visible[0]?.key ?? "id"] ?? row.id, visible[0] ?? {}, locale);
  const span = visible.length + (selectable ? 1 : 0);
  const hideable = columns.filter((column) => column.hideable);

  return (
    <div
      data-slot="data-table"
      data-surface="panel"
      className={cn("flex w-full min-w-0 flex-col overflow-hidden rounded-lg border bg-card text-card-foreground", className)}
    >
      {(selectable || (columnMenu && hideable.length > 0)) && (
        <div data-slot="data-table-toolbar" className="flex min-h-10 flex-wrap items-center justify-between gap-2 border-b px-3 py-2">
          <p className="text-sm text-muted-foreground tabular-nums" aria-live="polite">
            {selectable ? `${selected.size} of ${rows.length} selected` : ""}
          </p>
          {columnMenu && hideable.length > 0 && (
            <DropdownMenu sound={sound}>
              <DropdownMenuTrigger className={cn(buttonClass({ variant: "outline", size: "sm" }), "ms-auto gap-1.5")}>
                <ColumnsIcon size={16} />
                Columns
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuGroup>
                  <DropdownMenuLabel inset>Show columns</DropdownMenuLabel>
                  {hideable.map((column) => (
                    <DropdownMenuCheckboxItem
                      key={column.key}
                      checked={!hidden.has(column.key)}
                      // The last visible column stays: a table with no columns says nothing.
                      disabled={!hidden.has(column.key) && visible.length === 1}
                      onCheckedChange={(checked) => {
                        const next = new Set(hidden);
                        if (checked) next.delete(column.key);
                        else next.add(column.key);
                        const keys = columns.filter((c) => next.has(c.key)).map((c) => c.key);
                        setInnerHidden(keys);
                        onHiddenColumnsChange?.(keys);
                      }}
                    >
                      {column.header}
                    </DropdownMenuCheckboxItem>
                  ))}
                </DropdownMenuGroup>
              </DropdownMenuContent>
            </DropdownMenu>
          )}
        </div>
      )}
      <Table
        density={density}
        striped={striped}
        stickyHeader={stickyHeader}
        containerClassName={cn("rounded-none border-0 bg-transparent", containerClassName)}
        aria-busy={loading || undefined}
      >
        <TableCaption>{caption}</TableCaption>
        <TableHeader>
          <TableRow>
            {selectable && (
              <TableHead>
                <Checkbox
                  aria-label="Select all rows on this page"
                  sound={sound}
                  disabled={loading || pageIds.length === 0}
                  checked={pageIds.length > 0 && onPage === pageIds.length}
                  indeterminate={onPage > 0 && onPage < pageIds.length}
                  onCheckedChange={(checked) => {
                    const next = new Set(selected);
                    for (const id of pageIds) {
                      if (checked) next.add(id);
                      else next.delete(id);
                    }
                    setSelected(next);
                  }}
                />
              </TableHead>
            )}
            {visible.map((column) => {
              const at = sort.findIndex((rule) => rule.key === column.key);
              const rule = at >= 0 ? sort[at] : null;
              // One heading carries aria-sort: the first key. The others say their place in words.
              const ariaSort = at === 0 && rule ? ARIA_SORT[rule.direction] : column.sortable ? "none" : undefined;
              return (
                <TableHead key={column.key} numeric={NUMERIC(column)} aria-sort={ariaSort} className={cn(column.sortable && "px-1.5", column.className)}>
                  {column.sortable ? (
                    <button
                      type="button"
                      data-slot="data-table-sort"
                      onClick={(event) => setSort(nextSort(sort, column.key, event.shiftKey))}
                      className={cn(
                        "inline-flex h-7 max-w-full cursor-pointer items-center gap-1 rounded-sm px-1.5 font-medium whitespace-nowrap hover:bg-accent hover:text-accent-foreground",
                        "transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none",
                        "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",
                        rule && "text-foreground",
                        NUMERIC(column) && "flex-row-reverse",
                      )}
                    >
                      {column.header}
                      {rule?.direction === "asc" ? (
                        <ArrowUpIcon size={14} className="flex-none" />
                      ) : rule?.direction === "desc" ? (
                        <ArrowDownIcon size={14} className="flex-none" />
                      ) : (
                        <ChevronsUpDownIcon size={14} className="flex-none opacity-60" />
                      )}
                      {rule && sort.length > 1 && (
                        <span className="text-[0.6875rem] leading-none tabular-nums" aria-hidden="true">
                          {at + 1}
                        </span>
                      )}
                      {rule && at > 0 && <span className="sr-only">{`, sorted ${rule.direction === "asc" ? "ascending" : "descending"}, key ${at + 1}`}</span>}
                    </button>
                  ) : (
                    column.header
                  )}
                </TableHead>
              );
            })}
          </TableRow>
        </TableHeader>
        <TableBody>
          {loading ? (
            Array.from({ length: Math.min(Number.isFinite(size) ? size : 5, 5) }, (_, i) => (
              <TableRow key={`loading-${i}`} aria-hidden="true">
                {selectable && (
                  <TableCell>
                    <Skeleton className="size-4 rounded-[min(var(--radius-sm),5px)]" />
                  </TableCell>
                )}
                {visible.map((column) => (
                  <TableCell key={column.key}>
                    <Skeleton className={cn("h-3 rounded-sm", NUMERIC(column) ? "ms-auto w-12" : "w-24 max-w-full")} />
                  </TableCell>
                ))}
              </TableRow>
            ))
          ) : shown.length === 0 ? (
            <TableRow>
              <TableCell colSpan={Math.max(1, span)} className="h-24 text-center text-muted-foreground">
                {emptyLabel}
              </TableCell>
            </TableRow>
          ) : (
            shown.map((row) => {
              const on = selected.has(row.id);
              return (
                <TableRow key={row.id} selected={selectable ? on : undefined}>
                  {selectable && (
                    <TableCell>
                      <Checkbox
                        aria-label={`Select ${label(row)}`}
                        sound={sound}
                        checked={on}
                        onCheckedChange={(checked) => {
                          const next = new Set(selected);
                          if (checked) next.add(row.id);
                          else next.delete(row.id);
                          setSelected(next);
                        }}
                      />
                    </TableCell>
                  )}
                  {visible.map((column) => (
                    <TableCell key={column.key} numeric={NUMERIC(column)} className={column.className}>
                      {formatCell(row[column.key] ?? null, column, locale)}
                    </TableCell>
                  ))}
                </TableRow>
              );
            })
          )}
        </TableBody>
      </Table>
      {Number.isFinite(size) && (pageCount > 1 || pageSizeOptions) && (
        <div className="border-t px-3 py-2">
          <Pagination
            pageCount={pageCount}
            page={page}
            onPageChange={setPage}
            pageSizeOptions={pageSizeOptions}
            pageSize={size}
            onPageSizeChange={(next) => {
              setInnerSize(next);
              onPageSizeChange?.(next);
            }}
            sound={sound}
          />
        </div>
      )}
    </div>
  );
}

Files and dependencies

Adds
components/ui/data-table.tsx
Packages
None
Brings along
TableCheckboxButtonDropdown menuPaginationSkeletonSound engine
Icons
arrow-downarrow-upchevrons-up-downcolumns

Changelog

  1. 1.0.0 · 2026-12-03First release.

Loading index…

Keyboard shortcuts

/Ctrl KSearch components, docs and actions
?Show this list
AAppearance studio
SSound on or off
MFull or reduced motion
TTheme: auto, light, dark
GSurface: solid or frosted
BBackdrop photograph (under glass)
CCorner radius: square to round
RReplay the demo, on a component page
DDraw new data, on a component page
←→HomeEndMove the cursor in a focused chart
EscClose a dialog, or leave a chart cursor