Table
Rows ruled off by hand, three different lines so neighbours never match: striped, with ruled columns, sortable headings and an empty state.
| Invoice | Item | Status | Amount |
|---|---|---|---|
| INV-001 | Blue ballpoints, box of 50 | Paid | £12.50 |
| INV-002 | Cream notebooks, A5 | Pending | £24.00 |
| INV-003 | Fineliner set | Paid | £9.80 |
| INV-004 | Legal pads, pack of 6 | Refunded | £15.00 |
| Total | £61.30 | ||
import { Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow } from "@/components/ui/table";
const orders = [
["INV-001", "Blue ballpoints, box of 50", "Paid", "£12.50"],
["INV-002", "Cream notebooks, A5", "Pending", "£24.00"],
["INV-003", "Fineliner set", "Paid", "£9.80"],
["INV-004", "Legal pads, pack of 6", "Refunded", "£15.00"],
];
export default function TableDemo() {
return (
<Table>
<TableCaption>Recent orders.</TableCaption>
<TableHeader>
<TableRow>
<TableHead>Invoice</TableHead>
<TableHead>Item</TableHead>
<TableHead>Status</TableHead>
<TableHead className="text-right">Amount</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{orders.map(([invoice, item, status, amount]) => (
<TableRow key={invoice}>
<TableCell className="font-bold">{invoice}</TableCell>
<TableCell>{item}</TableCell>
<TableCell className="text-ink-2">{status}</TableCell>
<TableCell className="text-right tabular-nums">{amount}</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={3}>Total</TableCell>
<TableCell className="text-right tabular-nums">£61.30</TableCell>
</TableRow>
</TableFooter>
</Table>
);
}Installation
pnpm dlx shadcn@latest add @ballpoint/ tableimport type { ComponentProps, CSSProperties, ReactNode } from "react";
import { cn } from "@/lib/utils";
import { InkGlyph } from "@/lib/ink-glyphs";
import { inkRules } from "@/lib/ink";
import { hashSeed, verticalStroke } from "@/lib/ink-sketch";
// Rows are ruled off by hand: each row's ::after is painted in ink and
// masked by one of three drawn lines, so neighbouring rules differ and no
// row needs its own SVG. Column rules are the same trick turned upright.
const rule =
"relative after:pointer-events-none after:absolute after:inset-x-0 after:-bottom-[2.5px] after:h-[5px] after:bg-current after:[mask-image:var(--ink-rule-1)] after:[mask-size:100%_100%] after:[mask-repeat:no-repeat] nth-[3n+2]:after:[mask-image:var(--ink-rule-2)] nth-[3n]:after:[mask-image:var(--ink-rule-3)]";
const inkColumns: CSSProperties = Object.fromEntries(
[1, 2, 3].map((n) => {
const svg = `<svg xmlns='http://www.w3.org/2000/svg' viewBox='-1 0 6 100' preserveAspectRatio='none'><path d='${verticalStroke(hashSeed(`ink-col-${n}`), 100)}' fill='none' stroke='black' stroke-width='1.3' stroke-linecap='round'/></svg>`;
return [`--ink-col-${n}`, `url("data:image/svg+xml,${encodeURIComponent(svg)}")`];
}),
);
// With `columns`, every cell but the first in a row gets a rule down its left
// side, a different drawn line for each of three columns in turn.
const cols = "group-data-columns/table:not-first:before:pointer-events-none group-data-columns/table:not-first:before:absolute group-data-columns/table:not-first:before:inset-y-1.5 group-data-columns/table:not-first:before:left-0 group-data-columns/table:not-first:before:w-1 group-data-columns/table:not-first:before:bg-ink-4 group-data-columns/table:not-first:before:content-[''] group-data-columns/table:not-first:before:[mask-image:var(--ink-col-1)] group-data-columns/table:not-first:before:[mask-size:100%_100%] group-data-columns/table:nth-[3n+1]:before:[mask-image:var(--ink-col-2)] group-data-columns/table:nth-[3n]:before:[mask-image:var(--ink-col-3)]";
// A hatched wash for hover, selection and stripes: fine pen lines, not a tint.
const hatch = "repeating-linear-gradient(-50deg, color-mix(in oklab, var(--ink) 15%, transparent) 0 1px, transparent 1px 5px)";
/**
* Rows ruled off by hand. `variant="striped"` hatches every other row,
* `columns` rules the columns too, and `size="compact"` tightens the rows.
*/
function Table({
className,
style,
variant = "plain",
columns = false,
size = "default",
...props
}: ComponentProps<"table"> & {
/** Plain rows, or every other row hatched. */
variant?: "plain" | "striped";
/** Rule between the columns, by hand, the way the rows are. */
columns?: boolean;
size?: "default" | "compact";
}) {
return (
<div data-slot="table-container" className="relative w-full overflow-x-auto" style={{ ...inkRules, ...inkColumns, "--table-hatch": hatch } as CSSProperties}>
<table
data-slot="table"
data-variant={variant}
data-columns={columns ? "" : undefined}
data-size={size}
className={cn(
"group/table w-full caption-bottom text-base [--table-y:--spacing(3)] data-[size=compact]:[--table-y:--spacing(1.5)]",
"data-[variant=striped]:[&_tbody_tr:nth-child(even)]:bg-(image:--table-hatch)",
className,
)}
style={style}
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: ComponentProps<"thead">) {
return <thead data-slot="table-header" className={cn("[&_tr]:text-ink-line [&_tr]:after:h-[6px]", className)} {...props} />;
}
function TableBody({ className, ...props }: ComponentProps<"tbody">) {
return <tbody data-slot="table-body" className={cn("[&_tr:last-child]:after:hidden", className)} {...props} />;
}
function TableFooter({ className, ...props }: ComponentProps<"tfoot">) {
return <tfoot data-slot="table-footer" className={cn("font-bold [&>tr]:last:after:hidden", className)} {...props} />;
}
function TableRow({ className, ...props }: ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
rule,
"text-ink-4 transition-colors hover:bg-(image:--table-hatch) has-aria-expanded:bg-(image:--table-hatch) data-[state=selected]:bg-ink-5/40 data-[state=selected]:bg-(image:--table-hatch)",
className,
)}
{...props}
/>
);
}
/**
* A column heading. Give it `sort` (and `onSort`) to make it a button that
* sorts by the column: the pen's chevron points the way it is sorted, and the
* cell says so to assistive technology.
*/
function TableHead({ className, children, sort, onSort, ...props }: ComponentProps<"th"> & { sort?: "asc" | "desc" | "none"; onSort?: () => void }) {
const sortable = sort !== undefined;
return (
<th
data-slot="table-head"
aria-sort={sort === "asc" ? "ascending" : sort === "desc" ? "descending" : sortable ? "none" : undefined}
className={cn("relative h-11 px-3 text-left align-middle text-sm font-bold whitespace-nowrap text-ink-2 [&:has([role=checkbox])]:pr-0", cols, className)}
{...props}
>
{sortable ? (
<button type="button" onClick={onSort} className="group/sort -mx-2 inline-flex items-center gap-1 px-2 py-1 font-[inherit] text-[inherit] transition-colors hover:text-ink [th.text-right_&]:flex-row-reverse">
{children}
<span aria-hidden="true" className="relative inline-grid size-4 place-items-center">
{sort === "none" ? (
<>
<InkGlyph name="chevron-up" className="absolute size-3 -translate-y-[4.5px] opacity-40 transition-opacity group-hover/sort:opacity-90" />
<InkGlyph name="chevron-down" className="absolute size-3 translate-y-[4.5px] opacity-40 transition-opacity group-hover/sort:opacity-90" />
</>
) : (
<InkGlyph name={sort === "asc" ? "chevron-up" : "chevron-down"} className="size-4 text-ink" />
)}
</span>
</button>
) : (
children
)}
</th>
);
}
function TableCell({ className, ...props }: ComponentProps<"td">) {
return <td data-slot="table-cell" className={cn("relative px-3 py-(--table-y) align-middle whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0", cols, className)} {...props} />;
}
/** A row that says there is nothing here, across every column. */
function TableEmpty({ colSpan, className, children = "Nothing here yet." }: { colSpan: number; className?: string; children?: ReactNode }) {
return (
<TableRow className="hover:bg-transparent">
<TableCell colSpan={colSpan} className={cn("py-10 text-center whitespace-normal text-ink-3", className)}>
{children}
</TableCell>
</TableRow>
);
}
function TableCaption({ className, ...props }: ComponentProps<"caption">) {
return <caption data-slot="table-caption" className={cn("mt-4 text-sm text-ink-3", className)} {...props} />;
}
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableEmpty, TableCaption };Usage
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
<Table variant="striped" columns>
<TableHeader>
<TableRow>
<TableHead sort="asc" onSort={() => {}}>Invoice</TableHead>
<TableHead>Amount</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableCell>INV-001</TableCell>
<TableCell>£12.50</TableCell>
</TableRow>
</TableBody>
</Table>Examples
Striped, ruled, compact
Every other row hatched, the columns ruled by hand, and the rows tightened.
| Pen | Weeks | Pages | Used for |
|---|---|---|---|
| Blue ballpoint | 14 | 1,284 | Everyday |
| Black fineliner | 9 | 612 | Drawings |
| Pencil | 21 | 2,031 | Drafts |
| Green ink | 3 | 88 | Corrections |
| Red pen | 2 | 41 | Only when it matters |
import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
const pens = [
["Blue ballpoint", "14", "1,284", "Everyday"],
["Black fineliner", "9", "612", "Drawings"],
["Pencil", "21", "2,031", "Drafts"],
["Green ink", "3", "88", "Corrections"],
["Red pen", "2", "41", "Only when it matters"],
];
export default function TableStriped() {
return (
<Table variant="striped" columns size="compact">
<TableCaption>Pens in use this year.</TableCaption>
<TableHeader>
<TableRow>
<TableHead>Pen</TableHead>
<TableHead className="text-right">Weeks</TableHead>
<TableHead className="text-right">Pages</TableHead>
<TableHead>Used for</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{pens.map(([pen, weeks, pages, use]) => (
<TableRow key={pen}>
<TableCell className="font-bold">{pen}</TableCell>
<TableCell className="text-right tabular-nums">{weeks}</TableCell>
<TableCell className="text-right tabular-nums">{pages}</TableCell>
<TableCell className="text-ink-2">{use}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
);
}Sortable columns
A heading with sort is a button; its chevron points the way it is sorted.
| Katherine Johnson | Illustrator | 530 |
| Ada Lovelace | Writer | 412 |
| Grace Hopper | Editor | 268 |
| Mary Jackson | Writer | 97 |
"use client";
import { useMemo, useState } from "react";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
const rows = [
{ name: "Ada Lovelace", role: "Writer", pages: 412 },
{ name: "Grace Hopper", role: "Editor", pages: 268 },
{ name: "Katherine Johnson", role: "Illustrator", pages: 530 },
{ name: "Mary Jackson", role: "Writer", pages: 97 },
];
type Key = "name" | "role" | "pages";
export default function TableSortable() {
const [sort, setSort] = useState<{ key: Key; dir: "asc" | "desc" }>({ key: "pages", dir: "desc" });
const sorted = useMemo(() => {
const out = [...rows].sort((a, b) => (a[sort.key] > b[sort.key] ? 1 : a[sort.key] < b[sort.key] ? -1 : 0));
return sort.dir === "asc" ? out : out.reverse();
}, [sort]);
// A first press sorts a column one way, the next the other.
const press = (key: Key) => setSort((s) => ({ key, dir: s.key === key && s.dir === "asc" ? "desc" : "asc" }));
const state = (key: Key) => (sort.key === key ? sort.dir : "none");
return (
<Table>
<TableHeader>
<TableRow>
<TableHead sort={state("name")} onSort={() => press("name")}>
Name
</TableHead>
<TableHead sort={state("role")} onSort={() => press("role")}>
Role
</TableHead>
<TableHead className="text-right" sort={state("pages")} onSort={() => press("pages")}>
Pages
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sorted.map((row) => (
<TableRow key={row.name}>
<TableCell className="font-bold">{row.name}</TableCell>
<TableCell className="text-ink-2">{row.role}</TableCell>
<TableCell className="text-right tabular-nums">{row.pages}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
);
}Selectable rows
Checkboxes select rows; the header one is mixed when only some are picked.
| Name | Role | Status | |
|---|---|---|---|
| Ada Lovelace | Writer | Active | |
| Grace Hopper | Editor | Active | |
| Katherine Johnson | Illustrator | Away |
"use client";
import { useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
const rows = [
["Ada Lovelace", "Writer", "Active"],
["Grace Hopper", "Editor", "Active"],
["Katherine Johnson", "Illustrator", "Away"],
] as const;
export default function TableSelectable() {
const [picked, setPicked] = useState<string[]>(["Grace Hopper"]);
const all = picked.length === rows.length;
return (
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-10">
<Checkbox
aria-label="Select all"
checked={all}
indeterminate={picked.length > 0 && !all}
onCheckedChange={(on) => setPicked(on ? rows.map(([n]) => n) : [])}
seed="ts-all"
/>
</TableHead>
<TableHead>Name</TableHead>
<TableHead>Role</TableHead>
<TableHead className="text-right">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map(([name, role, status]) => (
<TableRow key={name} data-state={picked.includes(name) ? "selected" : undefined}>
<TableCell>
<Checkbox
aria-label={`Select ${name}`}
checked={picked.includes(name)}
onCheckedChange={(on) => setPicked((p) => (on ? [...p, name] : p.filter((x) => x !== name)))}
seed={`ts-${name}`}
/>
</TableCell>
<TableCell className="font-bold">{name}</TableCell>
<TableCell className="text-ink-2">{role}</TableCell>
<TableCell className="text-right">
<Badge variant={status === "Active" ? "default" : "outline"} seed={`ts-b-${name}`}>
{status}
</Badge>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
);
}Nothing to show
TableEmpty says so across every column, when a filter leaves no rows.
| Notebook | Paper | Pages |
|---|---|---|
| No notebook matches "zzz". Try "ruled". | ||
"use client";
import { useState } from "react";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableEmpty, TableHead, TableHeader, TableRow } from "@/components/ui/table";
const notebooks = [
["Cream A5", "Ruled", "96"],
["Legal pad", "Ruled", "50"],
["Sketchbook", "Plain", "120"],
["Graph pad", "Squared", "80"],
];
export default function TableEmptyExample() {
const [query, setQuery] = useState("zzz");
const shown = notebooks.filter(([name, kind]) => `${name} ${kind}`.toLowerCase().includes(query.trim().toLowerCase()));
return (
<div className="flex w-full flex-col gap-4">
<Input aria-label="Filter notebooks" placeholder="Filter notebooks" value={query} onChange={(event) => setQuery(event.target.value)} className="max-w-xs" />
<Table>
<TableHeader>
<TableRow>
<TableHead>Notebook</TableHead>
<TableHead>Paper</TableHead>
<TableHead className="text-right">Pages</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{shown.length ? (
shown.map(([name, kind, pages]) => (
<TableRow key={name}>
<TableCell className="font-bold">{name}</TableCell>
<TableCell className="text-ink-2">{kind}</TableCell>
<TableCell className="text-right tabular-nums">{pages}</TableCell>
</TableRow>
))
) : (
<TableEmpty colSpan={3}>No notebook matches "{query}". Try "ruled".</TableEmpty>
)}
</TableBody>
</Table>
</div>
);
}API reference
- variantdefault
"plain" "plain" | "striped"Plain rows, or every other row hatched with the pen.
- columnsdefault
false booleanRule the columns too: a different hand-drawn line for each, the way the rows are ruled.
- sizedefault
"default" "default" | "compact"Row height.
- TableHead sort
"asc" | "desc" | "none"Makes the heading a sort button. The chevron shows the direction, and the cell carries aria-sort.
- TableHead onSort
() => voidCalled when the sort button is pressed.
- TableRow
componentEach row is ruled off underneath by hand, three different lines so neighbours never match. Hovered and selected rows (data-state=selected) are hatched.
- TableEmpty
componentA row that says there is nothing here, across colSpan columns.
- TableFooter
componentTotals, set in bold under the rows.
- TableCaption
componentA note under the table, in lighter ink.