components / display
Data Table
Pieces that make a table useful: toolbar, sort, filter, select, paginate, row actions, status and user cells, and CSV export.
| Status | Actions | ||||
|---|---|---|---|---|---|
MA Marina Alves marina@helio.studio | Admin | active | |||
DS Davi Souza davi@helio.studio | Admin | active | |||
TF Tiago Ferraz tiago@orbit.foods | Editor | active | |||
JR Joana Reis joana@northwind.dev | Editor | invited | |||
CM Caio Mendes caio@acme.co | Viewer | active | |||
ID Inês Duarte ines@orbit.foods | Editor | invited |
data-table-users.tsx
"use client";
import { KeyRoundIcon, MailIcon, PlusIcon, UserXIcon } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
ColumnToggle,
type CsvColumn,
ExportCsvButton,
matchesQuery,
rowArrowKeys,
SortableHead,
TableBulkBar,
TableFilterChips,
TablePagination,
TableRelativeDate,
TableRowActions,
TableSearch,
TableSelectCell,
TableSelectHead,
TableStatus,
TableToolbar,
TableUser,
usePagination,
useSelection,
useSort,
} from "@/components/ui/data-table";
import { DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
import { Table, TableBody, TableCell, TableEmpty, TableHead, TableHeader, TableRow } from "@/components/ui/table";
const hour = 3_600_000;
const ago = (hours: number) => Date.now() - hours * hour;
type User = { id: string; name: string; email: string; role: string; status: "active" | "invited" | "suspended"; seen: number };
const initial: User[] = [
{ id: "u1", name: "Marina Alves", email: "marina@helio.studio", role: "Admin", status: "active", seen: ago(0.2) },
{ id: "u2", name: "Tiago Ferraz", email: "tiago@orbit.foods", role: "Editor", status: "active", seen: ago(5) },
{ id: "u3", name: "Joana Reis", email: "joana@northwind.dev", role: "Editor", status: "invited", seen: ago(30) },
{ id: "u4", name: "Caio Mendes", email: "caio@acme.co", role: "Viewer", status: "active", seen: ago(52) },
{ id: "u5", name: "Lara Costa", email: "lara@brightside.co", role: "Viewer", status: "suspended", seen: ago(400) },
{ id: "u6", name: "Davi Souza", email: "davi@helio.studio", role: "Admin", status: "active", seen: ago(3) },
{ id: "u7", name: "Inês Duarte", email: "ines@orbit.foods", role: "Editor", status: "invited", seen: ago(96) },
{ id: "u8", name: "Rui Lopes", email: "rui@northwind.dev", role: "Viewer", status: "active", seen: ago(210) },
];
const tone = { active: "success", invited: "warning", suspended: "danger" } as const;
const columns = [
{ id: "role", label: "Role" },
{ id: "status", label: "Status" },
{ id: "seen", label: "Last seen" },
] as const;
const csv: CsvColumn<User>[] = [
{ header: "Name", value: (u) => u.name },
{ header: "Email", value: (u) => u.email },
{ header: "Role", value: (u) => u.role },
{ header: "Status", value: (u) => u.status },
{ header: "Last seen", value: (u) => new Date(u.seen) },
];
export default function DataTableUsers() {
const [users, setUsers] = useState(initial);
const [query, setQuery] = useState("");
const [filter, setFilter] = useState("all");
const hidden = useSelection<string>();
const show = (id: string) => !hidden.has(id);
const filtered = users.filter((u) => (filter === "all" || u.status === filter) && matchesQuery(u, query));
const { rows, toggle, directionOf } = useSort(filtered, { key: "seen", direction: "desc" });
const pager = usePagination(rows.length, 6);
const page = pager.slice(rows);
const selection = useSelection(page.map((u) => u.id));
const remove = (ids: string[]) => {
setUsers((all) => all.filter((u) => !ids.includes(u.id)));
selection.clear();
};
const duplicate = (u: User) => setUsers((all) => [{ ...u, id: `${u.id}-copy`, name: `${u.name} (copy)`, status: "invited", seen: Date.now() }, ...all]);
const count = (status: string) => users.filter((u) => status === "all" || u.status === status).length;
return (
<div className="flex w-full flex-col gap-3">
<TableToolbar>
<TableSearch label="Search users" onValueChange={setQuery} placeholder="Search users" value={query} />
<TableFilterChips
label="Filter by status"
onValueChange={(id) => {
setFilter(id);
pager.setPage(0);
}}
options={[
{ id: "all", label: "All", count: count("all") },
{ id: "active", label: "Active", count: count("active") },
{ id: "invited", label: "Invited", count: count("invited") },
{ id: "suspended", label: "Suspended", count: count("suspended") },
]}
value={filter}
/>
<div className="flex flex-wrap items-center gap-2 sm:ms-auto">
<ColumnToggle columns={columns} hidden={hidden.selected} onToggle={hidden.toggle} />
<ExportCsvButton columns={csv} filename="users.csv" rows={rows} />
<Button className="rounded-md" size="sm" variant="brand">
<PlusIcon aria-hidden="true" />
Invite user
</Button>
</div>
</TableToolbar>
<TableBulkBar count={selection.selected.size} onClear={selection.clear}>
<Button className="rounded-md text-background hover:bg-background/15" onClick={() => remove([...selection.selected])} size="sm" variant="ghost">
Remove
</Button>
</TableBulkBar>
<Table aria-label="Users" density="comfortable">
<TableHeader>
<TableRow>
<TableSelectHead checked={selection.allSelected} indeterminate={selection.someSelected} onCheckedChange={selection.toggleAll} />
<SortableHead direction={directionOf("name")} onSort={() => toggle("name")}>
User
</SortableHead>
{show("role") && (
<SortableHead direction={directionOf("role")} onSort={() => toggle("role")}>
Role
</SortableHead>
)}
{show("status") && <TableHead>Status</TableHead>}
{show("seen") && (
<SortableHead direction={directionOf("seen")} onSort={() => toggle("seen")}>
Last seen
</SortableHead>
)}
<TableHead className="w-px">
<span className="sr-only">Actions</span>
</TableHead>
</TableRow>
</TableHeader>
<TableBody onKeyDown={rowArrowKeys}>
{page.length === 0 && <TableEmpty colSpan={6}>No user matches.</TableEmpty>}
{page.map((u) => (
<TableRow data-state={selection.has(u.id) ? "selected" : undefined} key={u.id}>
<TableSelectCell checked={selection.has(u.id)} label={`Select ${u.name}`} onCheckedChange={() => selection.toggle(u.id)} />
<TableCell>
<TableUser description={u.email} name={u.name} />
</TableCell>
{show("role") && <TableCell>{u.role}</TableCell>}
{show("status") && (
<TableCell>
<TableStatus tone={tone[u.status]}>{u.status}</TableStatus>
</TableCell>
)}
{show("seen") && (
<TableCell>
<TableRelativeDate date={u.seen} />
</TableCell>
)}
<TableRowActions
label={u.name}
menu={
<>
<DropdownMenuItem icon={<MailIcon />}>Resend invite</DropdownMenuItem>
<DropdownMenuItem icon={<KeyRoundIcon />}>Reset password</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem confirm icon={<UserXIcon />} variant="destructive">
Suspend
</DropdownMenuItem>
</>
}
onDelete={() => remove([u.id])}
onDuplicate={() => duplicate(u)}
onEdit={() => setQuery(u.name)}
/>
</TableRow>
))}
</TableBody>
</Table>
<TablePagination end={pager.end} onPageChange={pager.setPage} page={pager.page} pageCount={pager.pageCount} start={pager.start} total={rows.length} />
</div>
);
}Installation
$ npx shadcn@latest add https://cd-ui.vercel.app/r/data-table.jsonfirst time? set up components.json and the theme first: see installation.
Usage
import { SortableHead, matchesQuery, useSort } from "@/components/ui/data-table"
import { Table, TableBody, TableCell, TableHeader, TableRow } from "@/components/ui/table"
const { rows, toggle, directionOf } = useSort(users)
<Table>
<TableHeader>
<TableRow>
<SortableHead direction={directionOf("name")} onSort={() => toggle("name")}>Name</SortableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((u) => (
<TableRow key={u.id}>
<TableCell>{u.name}</TableCell>
</TableRow>
))}
</TableBody>
</Table>Examples
Invoices
Copyable ids, status with a dot, relative dates and money. A custom TableAction sits next to the delete button, which asks for a second click.
| Invoice | Status | Actions | ||||
|---|---|---|---|---|---|---|
| INV-1046 | Orbit Foods | pending | $3,075.00 | |||
| INV-1043 | Acme Logistics | pending | $890.00 | |||
| INV-1045 | Brightside Co. | failed | $640.00 | |||
| INV-1042 | Northwind Labs | paid | $2,450.00 | |||
| INV-1044 | Helio Studio | paid | $1,320.50 |
data-table-invoices.tsx
"use client";
import { CheckIcon } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
rowArrowKeys,
SortableHead,
TableAction,
TableBulkBar,
TableCopyId,
TableRelativeDate,
TableRowActions,
TableSelectCell,
TableSelectHead,
TableStatus,
useSelection,
useSort,
} from "@/components/ui/data-table";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
const day = 86_400_000;
const ago = (days: number) => Date.now() - days * day;
const initial = [
{ id: "INV-1042", customer: "Northwind Labs", status: "paid", amount: 2450, due: ago(2) },
{ id: "INV-1043", customer: "Acme Logistics", status: "pending", amount: 890, due: ago(-6) },
{ id: "INV-1044", customer: "Helio Studio", status: "paid", amount: 1320.5, due: ago(9) },
{ id: "INV-1045", customer: "Brightside Co.", status: "failed", amount: 640, due: ago(1) },
{ id: "INV-1046", customer: "Orbit Foods", status: "pending", amount: 3075, due: ago(-12) },
];
const tone = { paid: "success", pending: "warning", failed: "danger" } as const;
export default function DataTableInvoices() {
const [rows, setRows] = useState(initial);
const { rows: sorted, toggle, directionOf } = useSort(rows, { key: "due", direction: "desc" });
const selection = useSelection(
sorted.map((r) => r.id),
["INV-1043"],
);
const markPaid = (ids: readonly string[]) => {
setRows((all) => all.map((r) => (ids.includes(r.id) ? { ...r, status: "paid" } : r)));
selection.clear();
};
return (
<div className="flex w-full flex-col gap-3">
<TableBulkBar count={selection.selected.size} onClear={selection.clear}>
<Button className="rounded-md text-background hover:bg-background/15" onClick={() => markPaid([...selection.selected])} size="sm" variant="ghost">
<CheckIcon aria-hidden="true" />
Mark as paid
</Button>
</TableBulkBar>
<Table aria-label="Invoices">
<TableHeader>
<TableRow>
<TableSelectHead checked={selection.allSelected} indeterminate={selection.someSelected} onCheckedChange={selection.toggleAll} />
<TableHead>Invoice</TableHead>
<SortableHead direction={directionOf("customer")} onSort={() => toggle("customer")}>
Customer
</SortableHead>
<TableHead>Status</TableHead>
<SortableHead direction={directionOf("due")} onSort={() => toggle("due")}>
Due
</SortableHead>
<SortableHead direction={directionOf("amount")} numeric onSort={() => toggle("amount")}>
Amount
</SortableHead>
<TableHead className="w-px">
<span className="sr-only">Actions</span>
</TableHead>
</TableRow>
</TableHeader>
<TableBody onKeyDown={rowArrowKeys}>
{sorted.map((r) => (
<TableRow data-state={selection.has(r.id) ? "selected" : undefined} key={r.id}>
<TableSelectCell checked={selection.has(r.id)} label={`Select ${r.id}`} onCheckedChange={() => selection.toggle(r.id)} />
<TableCell>
<TableCopyId value={r.id} />
</TableCell>
<TableCell className="font-medium">{r.customer}</TableCell>
<TableCell>
<TableStatus tone={tone[r.status as keyof typeof tone]}>{r.status}</TableStatus>
</TableCell>
<TableCell>
<TableRelativeDate date={r.due} />
</TableCell>
<TableCell numeric>${r.amount.toLocaleString("en-US", { minimumFractionDigits: 2 })}</TableCell>
<TableRowActions label={r.id} onDelete={() => setRows((all) => all.filter((x) => x.id !== r.id))}>
{r.status !== "paid" && <TableAction icon={<CheckIcon aria-hidden="true" />} label={`Mark ${r.id} as paid`} onClick={() => markPaid([r.id])} />}
</TableRowActions>
</TableRow>
))}
</TableBody>
</Table>
</div>
);
}Expandable rows
The chevron opens a detail row under the line. It is a real button with aria-expanded, so it works with the keyboard.
| Details | Order | Customer | Status | Total |
|---|---|---|---|---|
| ORD-3021 | Helio Studio | shipped | $184.90 | |
| ORD-3022 | Orbit Foods | processing | $76.00 | |
| ORD-3023 | Northwind Labs | delivered | $512.35 | |
| ORD-3024 | Acme Logistics | processing | $39.50 |
data-table-expandable.tsx
"use client";
import { Fragment } from "react";
import { TableExpandButton, TableStatus, useSelection } from "@/components/ui/data-table";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
const orders = [
{ id: "ORD-3021", customer: "Helio Studio", status: "shipped", total: 184.9, items: ["Desk lamp x1", "USB-C hub x2", "Cable kit x1"] },
{ id: "ORD-3022", customer: "Orbit Foods", status: "processing", total: 76, items: ["Notebook x4"] },
{ id: "ORD-3023", customer: "Northwind Labs", status: "delivered", total: 512.35, items: ["Monitor arm x2", "Webcam x2", "Headset x2"] },
{ id: "ORD-3024", customer: "Acme Logistics", status: "processing", total: 39.5, items: ["Label printer rolls x5"] },
];
const tone = { shipped: "warning", processing: "neutral", delivered: "success" } as const;
export default function DataTableExpandable() {
const open = useSelection<string>();
return (
<Table aria-label="Orders">
<TableHeader>
<TableRow>
<TableHead className="w-12">
<span className="sr-only">Details</span>
</TableHead>
<TableHead>Order</TableHead>
<TableHead>Customer</TableHead>
<TableHead>Status</TableHead>
<TableHead numeric>Total</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{orders.map((o) => (
<Fragment key={o.id}>
<TableRow>
<TableCell className="w-12 pe-0">
<TableExpandButton controls={`${o.id}-details`} expanded={open.has(o.id)} label={`Show items of ${o.id}`} onToggle={() => open.toggle(o.id)} />
</TableCell>
<TableCell className="font-medium">{o.id}</TableCell>
<TableCell>{o.customer}</TableCell>
<TableCell>
<TableStatus tone={tone[o.status as keyof typeof tone]}>{o.status}</TableStatus>
</TableCell>
<TableCell numeric>${o.total.toFixed(2)}</TableCell>
</TableRow>
{open.has(o.id) && (
<TableRow className="hover:[--row-tint:transparent]" id={`${o.id}-details`}>
<TableCell className="bg-muted/50 text-muted-foreground" colSpan={5}>
<ul className="list-disc ps-12">
{o.items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</TableCell>
</TableRow>
)}
</Fragment>
))}
</TableBody>
</Table>
);
}API
useSort · matchesQuery · useSelection · usePagination
Hooks and a helper. They return plain values and never own your rows, so they also work with data from a server. useSelection is a set of ids kept across pages: use it for selected rows, open rows, or hidden columns.
| prop | type | default |
|---|
SortableHead · TableSelectHead · TableSelectCell · TableExpandButton
Header and cell pieces. SortableHead is a TableHead with a button inside.
| prop | type | default |
|---|---|---|
direction
| "asc" | "desc" | null | - |
onSortCalled when the header is activated. | () => void | - |
checkedWhether the row (or, in the header, every visible row) is selected. | boolean | - |
indeterminateShows a dash: some rows are selected, not all. | boolean | - |
labelAccessible name of the checkbox or button, for example "Select INV-1042". | string | - |
controlsThe | string | - |
TableBulkBar · ColumnToggle · TablePagination
Bars around the table: the bulk action bar, the column menu, and the pagination. Their texts are in English by default; label changes the column menu's.
| prop | type | default |
|---|---|---|
countHow many rows are selected. The bar renders nothing at 0. | number | - |
columnsThe columns that can be hidden, as | { id: string; label: string }[] | - |
hiddenThe ids of the hidden columns. | ReadonlySet<string> | - |
classNameExtra classes, merged with | string | - |
TableToolbar · TableSearch · TableFilterChips · ExportCsvButton · toCsv
The row above the table. TableSearch and TableFilterChips are controlled; filter with matchesQuery. ExportCsvButton downloads the rows you pass, so pass the filtered and sorted ones. Cells that start with = + - or @ are escaped.
| prop | type | default |
|---|---|---|
value · onValueChangeThe text of the search field. | string / (value) => void | - |
optionsThe chips. The one whose id equals | { id: string; label: string; count?: number }[] | - |
rows · columnsThe rows to export and how to read each column. | T[] / { header: string; value: (row) => ... }[] | - |
filenameName of the downloaded file. | string | "export.csv" |
classNameExtra classes, merged with | string | - |
TableRowActions · TableAction
TableRowActions is the last cell of a row: edit, duplicate and delete buttons (delete asks for a second click) and a "..." menu built from your DropdownMenuItems. They show on row hover or focus and stay visible on touch. TableAction is one icon button, to add your own.
| prop | type | default |
|---|---|---|
labelNames the row for screen readers, for example "Marina Alves". Each button says what it does to it. | string | - |
onEdit · onDuplicate · onDeleteA button shows only when its handler is passed. | () => void | - |
menuItems of the overflow menu. The button shows only when you pass this. | ReactNode | - |
childrenMore | ReactNode | - |
classNameExtra classes, merged with | string | - |
TableStatus · TableUser · TableCopyId · TableRelativeDate
Ready-made cells. TableStatus is text with a colored dot, TableUser an avatar with a name and a second line, TableCopyId a mono id with a copy button, and TableRelativeDate "3 days ago" with the full date as a tooltip.
| prop | type | default |
|---|---|---|
toneColor of the dot. The text still carries the meaning. | "success" | "warning" | "danger" | "neutral" | "neutral" |
name · description · srcName, second line and image. Without an image, the initials show. | string | - |
valueThe id to show and copy. | string | - |
date · now · localeThe date, an optional | Date | string | number | - |
rowArrowKeys
Optional. Pass rowArrowKeys as the onKeyDown of TableBody and Arrow Up and Arrow Down move focus to the same control in the previous or next row. Text fields and open menus keep their keys.
| prop | type | default |
|---|
Keyboard
| key | action |
|---|---|
| EnterSpace | Sorts by the focused column, opens the focused row, or toggles its checkbox. |
| ↑↓ | With `rowArrowKeys`, moves to the same control in the previous or next row. |
Accessibility
SortableHeadsetsaria-sorton the header, and the button inside is focusable. Only the sorted column reports a direction.- Every checkbox needs a
labelthat names its row. The bulk bar is a polite live region, so screen readers hear the count change. - Row action buttons are real buttons with a name like "Edit Marina Alves". They are only transparent until the row is hovered or focused, so keyboard users reach them with Tab. Delete announces that it needs another press.
- The chevron turns with a short transition that is dropped under reduced motion.