Data Table
A table of records with search, sorting, paging, tick boxes and a menu to hide columns. The Table with a little state in front of it; no table library.
| success | ken99@example.com | $316.00 | |
| success | abe45@example.com | $242.00 | |
| processing | monserrat44@example.com | $837.00 | |
| success | silas22@example.com | $874.00 | |
| failed | carmella@example.com | $721.00 |
"use client";
import { Badge } from "@/components/ui/badge";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
type Payment = { id: string; status: "pending" | "processing" | "success" | "failed"; email: string; amount: number };
const payments: Payment[] = [
{ id: "m5gr84i9", status: "success", email: "ken99@example.com", amount: 316 },
{ id: "3u1reuv4", status: "success", email: "abe45@example.com", amount: 242 },
{ id: "derv1ws0", status: "processing", email: "monserrat44@example.com", amount: 837 },
{ id: "5kma53ae", status: "success", email: "silas22@example.com", amount: 874 },
{ id: "bhqecj4p", status: "failed", email: "carmella@example.com", amount: 721 },
{ id: "p0ak2m1x", status: "pending", email: "jules@example.com", amount: 129 },
{ id: "q9w8e7r6", status: "success", email: "ines@example.com", amount: 460 },
{ id: "z1x2c3v4", status: "processing", email: "otto@example.com", amount: 98 },
];
const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const columns: DataTableColumn<Payment>[] = [
{
id: "status",
header: "Status",
sortable: true,
cell: (row) => (
<Badge variant={row.status === "failed" ? "destructive" : row.status === "success" ? "default" : "secondary"} size="sm" seed={`dt-${row.id}`}>
{row.status}
</Badge>
),
},
{ id: "email", header: "Email", sortable: true },
{ id: "amount", header: "Amount", sortable: true, align: "right", cell: (row) => money.format(row.amount) },
];
export default function DataTableDemo() {
return (
<div className="w-full max-w-2xl">
<DataTable columns={columns} data={payments} getRowId={(row) => row.id} pageSize={5} search="Filter emails…" selectable columnMenu caption="Payments" />
</div>
);
}Installation
pnpm dlx shadcn@latest add @ballpoint/ data-table"use client";
import { useMemo, useState, type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { InkGlyph } from "@/lib/ink-glyphs";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuLabel, DropdownMenuGroup, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableEmpty, TableHead, TableHeader, TableRow } from "@/components/ui/table";
// A table with the things a table of records is usually asked for: search,
// sorting, paging, ticking rows and hiding columns. It is the Table, with a
// little state in front of it, so there is no table library to learn.
type Sortable = string | number | boolean | Date | null | undefined;
export type DataTableColumn<T> = {
/** The column's key: the name of a field of the row, unless `accessor` says otherwise. */
id: string;
header: ReactNode;
/** The value that sorting and searching look at. */
accessor?: (row: T) => Sortable;
/** What the cell shows. By default the value, written plainly. */
cell?: (row: T) => ReactNode;
/** Sort by clicking the heading. */
sortable?: boolean;
/** Include the column in the search. */
searchable?: boolean;
/** Offer the column in the Columns menu. */
hideable?: boolean;
align?: "left" | "right";
className?: string;
};
type Sort = { id: string; dir: "asc" | "desc" };
function compare(a: Sortable, b: Sortable) {
if (a == null && b == null) return 0;
if (a == null) return 1;
if (b == null) return -1;
if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();
if (typeof a === "number" && typeof b === "number") return a - b;
return String(a).localeCompare(String(b), undefined, { numeric: true, sensitivity: "base" });
}
function DataTable<T extends object>({
columns,
data,
getRowId = (_row, index) => String(index),
pageSize = 10,
search = false,
selectable = false,
onSelectionChange,
defaultSort,
columnMenu = false,
empty = "No results.",
toolbar,
caption,
className,
}: {
columns: DataTableColumn<T>[];
data: T[];
getRowId?: (row: T, index: number) => string;
/** Rows to a page, or false to show them all. */
pageSize?: number | false;
/** A search field above the table. Give it a string to set its placeholder. */
search?: boolean | string;
/** A tick box on every row. */
selectable?: boolean;
onSelectionChange?: (rows: T[]) => void;
defaultSort?: Sort;
/** A Columns menu to hide and show columns. */
columnMenu?: boolean;
empty?: ReactNode;
/** More to put in the bar above the table. */
toolbar?: ReactNode;
caption?: string;
className?: string;
}) {
const [query, setQuery] = useState("");
const [sort, setSort] = useState<Sort | null>(defaultSort ?? null);
const [page, setPage] = useState(0);
const [selected, setSelected] = useState<Set<string>>(new Set());
const [hidden, setHidden] = useState<Set<string>>(new Set());
const valueOf = (column: DataTableColumn<T>, row: T): Sortable => (column.accessor ? column.accessor(row) : ((row as Record<string, Sortable>)[column.id] ?? null));
const shown = columns.filter((column) => !hidden.has(column.id));
const rows = useMemo(() => {
const entries = data.map((row, index) => ({ row, id: getRowId(row, index) }));
const needle = query.trim().toLowerCase();
const found = needle
? entries.filter(({ row }) => columns.some((column) => column.searchable !== false && String(valueOf(column, row) ?? "").toLowerCase().includes(needle)))
: entries;
const by = sort && columns.find((column) => column.id === sort.id);
if (!by) return found;
const sorted = [...found].sort((a, b) => compare(valueOf(by, a.row), valueOf(by, b.row)));
return sort.dir === "asc" ? sorted : sorted.reverse();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data, query, sort, columns]);
const pages = pageSize ? Math.max(1, Math.ceil(rows.length / pageSize)) : 1;
const current = Math.min(page, pages - 1);
const visible = pageSize ? rows.slice(current * pageSize, (current + 1) * pageSize) : rows;
const change = (next: Set<string>) => {
setSelected(next);
onSelectionChange?.(data.filter((row, index) => next.has(getRowId(row, index))));
};
const onPage = visible.filter(({ id }) => selected.has(id)).length;
const toggleRow = (id: string, on: boolean) => {
const next = new Set(selected);
if (on) next.add(id);
else next.delete(id);
change(next);
};
const togglePage = (on: boolean) => {
const next = new Set(selected);
for (const { id } of visible) {
if (on) next.add(id);
else next.delete(id);
}
change(next);
};
const press = (id: string) => setSort((s) => (s?.id === id ? (s.dir === "asc" ? { id, dir: "desc" } : null) : { id, dir: "asc" }));
return (
<div data-slot="data-table" className={cn("flex w-full flex-col gap-4", className)}>
{(search || columnMenu || toolbar) && (
<div className="flex flex-wrap items-center gap-3">
{search && (
<Input
type="search"
aria-label="Search the table"
placeholder={typeof search === "string" ? search : "Search…"}
value={query}
onChange={(event) => {
setQuery(event.target.value);
setPage(0);
}}
className="max-w-xs"
seed="data-table-search"
/>
)}
<div className="ml-auto flex items-center gap-3">
{toolbar}
{columnMenu && (
<DropdownMenu>
<DropdownMenuTrigger render={<Button variant="outline" seed="data-table-columns" />}>
Columns <InkGlyph name="chevron-down" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuGroup>
<DropdownMenuLabel>Show columns</DropdownMenuLabel>
{columns
.filter((column) => column.hideable !== false)
.map((column) => (
<DropdownMenuCheckboxItem
key={column.id}
checked={!hidden.has(column.id)}
onCheckedChange={(on) =>
setHidden((set) => {
const next = new Set(set);
if (on) next.delete(column.id);
else next.add(column.id);
return next;
})
}
>
{typeof column.header === "string" ? column.header : column.id}
</DropdownMenuCheckboxItem>
))}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</div>
)}
<Table>
{caption && <caption className="sr-only">{caption}</caption>}
<TableHeader>
<TableRow>
{selectable && (
<TableHead className="w-10">
<Checkbox
aria-label="Select all rows on this page"
checked={visible.length > 0 && onPage === visible.length}
indeterminate={onPage > 0 && onPage < visible.length}
onCheckedChange={togglePage}
seed="data-table-all"
/>
</TableHead>
)}
{shown.map((column) => (
<TableHead
key={column.id}
className={cn(column.align === "right" && "text-right", column.className)}
sort={column.sortable ? (sort?.id === column.id ? sort.dir : "none") : undefined}
onSort={column.sortable ? () => press(column.id) : undefined}
>
{column.header}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{visible.length ? (
visible.map(({ row, id }) => (
<TableRow key={id} data-state={selected.has(id) ? "selected" : undefined}>
{selectable && (
<TableCell>
<Checkbox aria-label="Select row" checked={selected.has(id)} onCheckedChange={(on) => toggleRow(id, on)} seed={`data-table-${id}`} />
</TableCell>
)}
{shown.map((column) => (
<TableCell key={column.id} className={cn(column.align === "right" && "text-right tabular-nums", column.className)}>
{column.cell ? column.cell(row) : String(valueOf(column, row) ?? "")}
</TableCell>
))}
</TableRow>
))
) : (
<TableEmpty colSpan={shown.length + (selectable ? 1 : 0)}>{empty}</TableEmpty>
)}
</TableBody>
</Table>
{(selectable || pageSize) && (
<div className="flex flex-wrap items-center gap-3 text-sm text-ink-3">
{selectable && (
<div role="status" aria-live="polite">
{selected.size} of {data.length} row{data.length === 1 ? "" : "s"} selected.
</div>
)}
{pageSize && (
<div className="ml-auto flex items-center gap-3">
<span>
Page {current + 1} of {pages}
</span>
<Button variant="outline" size="sm" disabled={current === 0} onClick={() => setPage(current - 1)} seed="data-table-prev">
Previous
</Button>
<Button variant="outline" size="sm" disabled={current >= pages - 1} onClick={() => setPage(current + 1)} seed="data-table-next">
Next
</Button>
</div>
)}
</div>
)}
</div>
);
}
export { DataTable };Usage
import { DataTable, type DataTableColumn } from "@/components/ui/data-table"
const columns: DataTableColumn<Payment>[] = [
{ id: "email", header: "Email", sortable: true },
{ id: "amount", header: "Amount", sortable: true, align: "right" },
]
<DataTable columns={columns} data={payments} search selectable />Examples
Sorting only
No toolbar and no paging, opening sorted by one column.
| Charcoal | Charcoal | 3 |
| Felt tip | Ink | 1.2 |
| HB pencil | Graphite | 0.9 |
| Blue ballpoint | Ink | 0.7 |
| Black gel | Ink | 0.5 |
"use client";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
type Pen = { name: string; kind: string; weight: number };
const pens: Pen[] = [
{ name: "Blue ballpoint", kind: "Ink", weight: 0.7 },
{ name: "Black gel", kind: "Ink", weight: 0.5 },
{ name: "HB pencil", kind: "Graphite", weight: 0.9 },
{ name: "Felt tip", kind: "Ink", weight: 1.2 },
{ name: "Charcoal", kind: "Charcoal", weight: 3 },
];
const columns: DataTableColumn<Pen>[] = [
{ id: "name", header: "Pen", sortable: true },
{ id: "kind", header: "Kind", sortable: true },
{ id: "weight", header: "Line (mm)", sortable: true, align: "right" },
];
export default function DataTableSimple() {
return (
<div className="w-full max-w-lg">
<DataTable columns={columns} data={pens} pageSize={false} defaultSort={{ id: "weight", dir: "desc" }} />
</div>
);
}Row actions
A menu on every row; the data is yours, so removing a row is a state change.
| Edited | Actions | |
|---|---|---|
| Letter to Ada | Today | |
| Margin sketches | Yesterday | |
| Shopping list | Monday |
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { InkIcon } from "@/components/ui/ink-icons";
type Note = { id: number; title: string; edited: string };
const initial: Note[] = [
{ id: 1, title: "Letter to Ada", edited: "Today" },
{ id: 2, title: "Margin sketches", edited: "Yesterday" },
{ id: 3, title: "Shopping list", edited: "Monday" },
];
export default function DataTableActions() {
const [notes, setNotes] = useState(initial);
const columns: DataTableColumn<Note>[] = [
{ id: "title", header: "Note", sortable: true },
{ id: "edited", header: "Edited" },
{
id: "actions",
header: <span className="sr-only">Actions</span>,
hideable: false,
searchable: false,
align: "right",
cell: (note) => (
<DropdownMenu>
<DropdownMenuTrigger render={<Button variant="ghost" size="icon-sm" aria-label={`Actions for ${note.title}`} seed={`dta-${note.id}`} />}>
<InkIcon name="more" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => navigator.clipboard?.writeText(note.title)}>Copy title</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onClick={() => setNotes((all) => all.filter((n) => n.id !== note.id))}>
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
),
},
];
return (
<div className="w-full max-w-lg">
<DataTable columns={columns} data={notes} getRowId={(note) => String(note.id)} pageSize={false} empty="No notes left." />
</div>
);
}API reference
- columns
DataTableColumn<T>[]id (the row's field), header, and optionally accessor, cell, sortable, searchable, hideable, align.
- data
T[]The rows.
- getRowIddefault
index (row, index) => stringA stable key for each row. Needed to keep selection when data changes.
- pageSizedefault
10 number | falseRows to a page, or false for no paging.
- searchdefault
false boolean | stringA search field over every searchable column. A string sets its placeholder.
- selectable / onSelectionChangedefault
false boolean / (rows: T[]) => voidA tick box on every row and one for the page, and what is ticked.
- columnMenudefault
false booleanA Columns menu to hide and show columns.
- defaultSort
{ id: string; dir: 'asc' | 'desc' }How it opens.
- toolbar / empty / caption
ReactNode / ReactNode / stringMore for the bar above; what to say when no row matches; a name for screen readers.