Skip to content
ProLifetime access for $199, paid once, every future release included
Truffle UI

Table

FreeNew

Table parts with sortable headers, row selection, a sticky header, a pinned column, loading and empty rows, and rows that become labelled cards on narrow containers.

Installation

pnpm dlx shadcn@latest add @viewport/table

First time? Add the @viewport registry to components.json. Setup takes one minute.

Usage

The code behind the preview above.

table-demo.tsx
"use client";

import { useMemo, useState } from "react";
import { Badge } from "@/components/viewport/badge";
import { Checkbox } from "@/components/viewport/checkbox";
import { Table, TableBody, TableCell, TableEmpty, TableHead, TableHeader, TableRow, TableSkeleton } from "@/components/viewport/table";

const invoices = [
  { id: "INV-2041", customer: "Northwind Trading", status: "Paid", due: "2026-11-28", amount: 12400 },
  { id: "INV-2042", customer: "Globex", status: "Overdue", due: "2026-11-30", amount: 3180 },
  { id: "INV-2043", customer: "Initech", status: "Open", due: "2026-12-12", amount: 860 },
  { id: "INV-2044", customer: "Umbrella Health", status: "Paid", due: "2026-12-01", amount: 24950 },
  { id: "INV-2045", customer: "Hooli", status: "Open", due: "2026-12-20", amount: 5400 },
];
const tone = { Paid: "success", Open: "info", Overdue: "danger" } as const;
type Key = "customer" | "due" | "amount";

export default function TableDemo() {
  const [sort, setSort] = useState<{ key: Key; dir: "asc" | "desc" }>({ key: "due", dir: "asc" });
  const [selected, setSelected] = useState<string[]>(["INV-2042"]);
  const [state, setState] = useState<"data" | "loading" | "empty">("data");

  const rows = useMemo(() => [...invoices].sort((a, b) => (a[sort.key] < b[sort.key] ? -1 : a[sort.key] > b[sort.key] ? 1 : 0) * (sort.dir === "asc" ? 1 : -1)), [sort]);
  const cycle = (key: Key) => setSort((s) => ({ key, dir: s.key === key && s.dir === "asc" ? "desc" : "asc" }));
  const dir = (key: Key) => (sort.key === key ? sort.dir : null);
  const all = selected.length === rows.length ? true : selected.length ? "indeterminate" : false;

  return (
    <div className="flex w-full max-w-2xl flex-col gap-3">
      <div className="overflow-hidden rounded-2xl border border-border bg-card">
        <Table stack label="Invoices" aria-busy={state === "loading"}>
          <TableHeader>
            <TableRow>
              <TableHead className="w-10">
                <Checkbox aria-label="Select all invoices" checked={all} onCheckedChange={(v) => setSelected(v === true ? rows.map((r) => r.id) : [])} />
              </TableHead>
              <TableHead sort={dir("customer")} onSort={() => cycle("customer")}>
                Customer
              </TableHead>
              <TableHead>Status</TableHead>
              <TableHead sort={dir("due")} onSort={() => cycle("due")}>
                Due
              </TableHead>
              <TableHead numeric sort={dir("amount")} onSort={() => cycle("amount")}>
                Amount
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {state === "loading" ? <TableSkeleton rows={5} columns={5} /> : null}
            {state === "empty" ? <TableEmpty colSpan={5}>No invoices match. Try a different period.</TableEmpty> : null}
            {state === "data"
              ? rows.map((row) => (
                  <TableRow key={row.id} selected={selected.includes(row.id)}>
                    <TableCell label="Select">
                      <Checkbox aria-label={`Select ${row.id}`} checked={selected.includes(row.id)} onCheckedChange={(v) => setSelected((list) => (v === true ? [...list, row.id] : list.filter((id) => id !== row.id)))} />
                    </TableCell>
                    <TableCell label="Customer">
                      <span className="font-medium">{row.customer}</span> <span className="text-muted-foreground">{row.id}</span>
                    </TableCell>
                    <TableCell label="Status">
                      <Badge tone={tone[row.status as keyof typeof tone]} dot>
                        {row.status}
                      </Badge>
                    </TableCell>
                    <TableCell label="Due" className="tabular-nums text-muted-foreground">
                      {new Date(`${row.due}T00:00`).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                    </TableCell>
                    <TableCell label="Amount" numeric>
                      {row.amount.toLocaleString("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 })}
                    </TableCell>
                  </TableRow>
                ))
              : null}
          </TableBody>
        </Table>
      </div>
      <div role="group" aria-label="Table state" className="flex justify-center gap-1.5">
        {(["data", "loading", "empty"] as const).map((s) => (
          <button
            key={s}
            type="button"
            aria-pressed={state === s}
            onClick={() => setState(s)}
            className="h-7 cursor-pointer rounded-full border border-border px-3 text-xs font-medium capitalize outline-none transition-colors hover:bg-foreground/[0.06] focus-visible:ring-2 focus-visible:ring-ring aria-pressed:border-foreground aria-pressed:bg-foreground aria-pressed:text-background"
          >
            {s}
          </button>
        ))}
      </div>
    </div>
  );
}

Props

<Table>

PropTypeDefault
density"comfortable" | "compact"

Row height: `compact` fits more rows on screen.

"comfortable"
stickyHeaderboolean

Keep the header in view while the body scrolls. Limit the height with `containerClassName`, e.g. `max-h-96`.

false
stackboolean

Turn each row into a labelled card when the table's own container is narrower than 36rem. Give every cell a `label`.

false
labelstring

Names the scrolling region and makes it focusable, so it can be scrolled with the keyboard.

—
containerClassNamestring

Classes for the scrolling wrapper around the table.

—

<TableRow>

PropTypeDefault
selectedboolean

Tints the row and marks it selected for assistive technology.

—

<TableHead>

PropTypeDefault
sort"asc" | "desc" | null

The column's current sort. Pass it together with `onSort` to make the header a sort button.

—
onSort() => void

Runs when the header is pressed. Cycle the sort in your own state.

—
numericboolean

Align to the end, for numbers.

—
pinnedboolean

Keep this column in view while the table scrolls sideways. Use it on the first column.

—
transitionNamestring

A name unique on the page, e.g. the column id. With `tableTransition`, the header slides when its column moves.

—

<TableCell>

PropTypeDefault
numericboolean

Align to the end and use tabular numerals.

—
pinnedboolean

Keep this cell in view while the table scrolls sideways. Match the pinned header.

—
labelstring

The column's name, shown beside the value when the table is stacked.

—

<TableEmpty>

PropTypeDefault
colSpan*number

The number of columns in the table, so the message spans all of them.

—

<TableSkeleton>

PropTypeDefault
rowsnumber

How many placeholder rows to draw. Use the page size, so the table does not change height when data arrives.

5
columns*number

The number of columns in the table.

—

Accessibility

  • Real table markup with explicit roles, so it stays a table when rows are stacked.
  • Sortable headers are buttons and set aria-sort; selected rows set aria-selected.
  • With a label the scrolling region is focusable and named.
  • Stacking follows the table's own width, not the viewport's.