Data Table
SaveA table with column sorting, a text filter, checkbox row selection, pagination, and empty states, built on Table without a table library.
- Category
- Data display
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Data Table preview
| Run | ||||||
|---|---|---|---|---|---|---|
| run_4f2a | docs-writer | Succeeded | 4s | 1,800 | 9:58 AM | |
| run_50b7 | sql-analyst | Succeeded | 12s | 17,285 | 9:51 AM | |
| run_5244 | test-fixer | Failed | 20s | 32,770 | 9:44 AM | |
| run_53d1 | migration-planner | Succeeded | 28s | 48,255 | 9:37 AM | |
| run_555e | release-notes | Running | In progress | 63,740 | 9:30 AM | |
| run_56eb | triage | Succeeded | 44s | 79,225 | 9:23 AM | |
| run_5878 | docs-writer | Needs approval | In progress | 94,710 | 9:16 AM | |
| run_5a05 | sql-analyst | Succeeded | 1m 00s | 14,195 | 9:09 AM |
1 to 8 of 27
Installation
npx @shakenui/cli add data-tableReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add data-table --dry-runUsage
data-table-example.tsx
"use client";
import { Button } from "@/components/shaken/ui/button";
import { DataTable, type DataTableColumn } from "@/components/shaken/ui/data-table";
type Run = {
id: string;
agent: string;
status: "succeeded" | "failed" | "running" | "waiting";
durationMs: number | null;
tokens: number;
started: Date;
};
const agents = ["docs-writer", "triage", "release-notes", "migration-planner", "test-fixer", "sql-analyst"];
const statuses: Run["status"][] = ["succeeded", "succeeded", "failed", "succeeded", "running", "succeeded", "waiting", "succeeded"];
const runs: Run[] = Array.from({ length: 27 }, (_, i) => {
const status = statuses[i % statuses.length]!;
return {
id: `run_${(0x4f2a + i * 397).toString(16)}`,
agent: agents[(i * 5) % agents.length]!,
status,
durationMs: status === "running" || status === "waiting" ? null : 4_200 + ((i * 7_919) % 180_000),
tokens: 1_800 + ((i * 15_485) % 96_000),
started: new Date(2026, 10, 14, 9, 58 - i * 7),
};
});
const tone: Record<Run["status"], string> = {
succeeded: "bg-emerald-500",
failed: "bg-red-500",
running: "bg-sky-500",
waiting: "bg-amber-500",
};
const label: Record<Run["status"], string> = {
succeeded: "Succeeded",
failed: "Failed",
running: "Running",
waiting: "Needs approval",
};
const time = new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit" });
const number = new Intl.NumberFormat("en-US");
function duration(ms: number) {
const seconds = Math.round(ms / 1000);
return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, "0")}s`;
}
const columns: DataTableColumn<Run>[] = [
{
id: "id",
header: "Run",
cell: (run) => <span className="font-mono text-xs text-zinc-600 dark:text-zinc-400">{run.id}</span>,
},
{ id: "agent", header: "Agent", sortable: true, cell: (run) => <span className="font-medium">{run.agent}</span> },
{
id: "status",
header: "Status",
sortable: true,
accessor: (run) => label[run.status],
cell: (run) => (
<span className="inline-flex items-center gap-2 whitespace-nowrap text-zinc-700 dark:text-zinc-300">
<span aria-hidden="true" className={`size-1.5 rounded-full ${tone[run.status]}`} />
{label[run.status]}
</span>
),
},
{
id: "durationMs",
header: "Duration",
numeric: true,
sortable: true,
cell: (run) => (run.durationMs === null ? <span className="text-zinc-400 dark:text-zinc-600">In progress</span> : duration(run.durationMs)),
},
{ id: "tokens", header: "Tokens", numeric: true, sortable: true, cell: (run) => number.format(run.tokens) },
{
id: "started",
header: "Started",
numeric: true,
sortable: true,
cell: (run) => <span className="text-zinc-600 dark:text-zinc-400">{time.format(run.started)}</span>,
},
];
export default function DataTableExample() {
return (
<DataTable
className="w-full max-w-3xl"
caption="Agent runs today"
captionHidden
columns={columns}
data={runs}
getRowId={(run) => run.id}
getRowLabel={(run) => `${run.id}, ${run.agent}`}
selectable
filterable
filterPlaceholder="Filter by run or agent"
defaultSort={{ id: "started", direction: "desc" }}
pageSize={8}
selectionActions={() => (
<Button variant="secondary" size="sm">
Re-run
</Button>
)}
/>
);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| columns | DataTableColumn<Row>[] | ā | Column definitions: id, header, accessor, cell, sortable, sortFn, filterable, numeric, className, headerClassName. |
| data | Row[] | ā | The rows. |
| getRowId | (row) => string | ā | Stable id per row, used for selection and keys. |
| getRowLabel | (row) => string | ā | Names a row in its checkbox label. Defaults to the id. |
| caption / captionHidden | string / boolean | ā | Accessible name for the table, optionally visually hidden. |
| selectable | boolean | false | Adds a checkbox column with a select-all-on-page header checkbox. |
| selected / defaultSelected / onSelectedChange | string[] / string[] / (ids) => void | ā | Selection state, controlled or not. |
| selectionActions | (ids) => ReactNode | ā | Toolbar buttons shown while rows are selected. |
| filterable / filterPlaceholder | boolean / string | false | Shows a search field that filters by string columns or columns marked filterable. |
| filter / onFilterChange | string / (value) => void | ā | Filter text, controlled. |
| sort / defaultSort / onSortChange | { id, direction } | null | ā | Sort state. Header buttons cycle ascending, descending, off. |
| pageSize | number | 10 | Rows per page. 0 turns pagination off. |
| empty | ReactNode | ā | Shown when data is empty. A filter with no matches shows its own message with a clear button. |
| toolbar | ReactNode | ā | Extra controls at the end of the toolbar. |
| stickyHeader / density / tableClassName | boolean / "default" | "compact" / string | ā | Passed to Table. |
Accessibility
- Sortable headers are buttons inside th elements that carry aria-sort (ascending, descending, or none).
- Checkboxes are Base UI Checkbox with an aria-label per row ("Select run_4f2a, docs-writer"); the header checkbox shows a mixed state when some rows on the page are selected.
- The row count and page range sit in a polite live region, and the filter field is described by it, so filtering announces how many rows match.
- Pagination buttons are labelled "Previous page" and "Next page" inside a nav named Pagination, and are disabled at the ends.
- A filter with no matches keeps the table structure and offers a Clear filter button.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/ui/data-table.tsxdata-table- Also installs table@0.1.0registry dependency
- Also installs button@0.2.1registry dependency
- Also installs input@0.1.1registry dependency
- npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/data-table/0.1.0.json.
ui/data-table.tsxShowHide
ui/data-table.tsx
"use client";
import { Checkbox } from "@base-ui/react/checkbox";
import { type ReactNode, useEffect, useId, useMemo, useState } from "react";
import { Button } from "./button";
import { Input } from "./input";
import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "./table";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
export type SortDirection = "asc" | "desc";
export type DataTableSort = { id: string; direction: SortDirection } | null;
type Sortable = string | number | boolean | Date | null | undefined;
export interface DataTableColumn<Row> {
/** Stable id, used for sorting state and React keys. */
id: string;
header: ReactNode;
/** The raw value for sorting and filtering. Defaults to `row[id]`. */
accessor?: (row: Row) => Sortable;
/** Renders the cell. Defaults to the accessor value as text. */
cell?: (row: Row) => ReactNode;
/** Shows a sort button in the header. */
sortable?: boolean;
/** Custom comparison for ascending order. */
sortFn?: (a: Row, b: Row) => number;
/** Whether the text filter searches this column. Defaults to true for string values. */
filterable?: boolean;
/** Right-aligns the column with tabular figures. */
numeric?: boolean;
/** Classes for every body cell in this column, for example a width. */
className?: string;
/** Classes for the header cell. */
headerClassName?: string;
}
export interface DataTableProps<Row> {
columns: DataTableColumn<Row>[];
data: Row[];
/** A stable id per row, used for selection. */
getRowId: (row: Row) => string;
/** How a row is named in its checkbox label ("Select checkout-api"). Defaults to the row id. */
getRowLabel?: (row: Row) => string;
/** Names the table for assistive technology. Shown below the table unless `captionHidden`. */
caption: string;
captionHidden?: boolean;
/** Adds a checkbox column. */
selectable?: boolean;
/** Selected row ids (controlled). */
selected?: string[];
defaultSelected?: string[];
onSelectedChange?: (ids: string[]) => void;
/** Buttons shown in the toolbar while rows are selected, for example a bulk action. */
selectionActions?: (ids: string[]) => ReactNode;
/** Shows a search field that filters rows by the filterable columns. */
filterable?: boolean;
filterPlaceholder?: string;
/** Filter text (controlled). */
filter?: string;
onFilterChange?: (value: string) => void;
/** Extra controls at the end of the toolbar. */
toolbar?: ReactNode;
/** Sort state (controlled). `null` keeps the data order. */
sort?: DataTableSort;
defaultSort?: DataTableSort;
onSortChange?: (sort: DataTableSort) => void;
/** Rows per page. `0` turns pagination off. */
pageSize?: number;
/** Shown when `data` is empty. A filter with no matches has its own message. */
empty?: ReactNode;
stickyHeader?: boolean;
density?: "default" | "compact";
className?: string;
/** Classes for the table's scroll container, for example a max height with `stickyHeader`. */
tableClassName?: string;
}
function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (value: T) => void) {
const [inner, setInner] = useState(defaultValue);
const controlled = value !== undefined;
const current = controlled ? value : inner;
const set = (next: T) => {
if (!controlled) setInner(next);
onChange?.(next);
};
return [current, set] as const;
}
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
function compare(a: Sortable, b: Sortable) {
// Empty values sort last in both directions; the caller flips only the populated part.
if (a == null || a === "") return b == null || b === "" ? 0 : 1;
if (b == null || b === "") return -1;
if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();
if (typeof a === "number" && typeof b === "number") return a - b;
if (typeof a === "boolean" && typeof b === "boolean") return Number(a) - Number(b);
return collator.compare(String(a), String(b));
}
function readValue<Row>(column: DataTableColumn<Row>, row: Row): Sortable {
if (column.accessor) return column.accessor(row);
return (row as Record<string, Sortable>)[column.id];
}
/**
* A table with sorting, a text filter, row selection, and pagination, built on `Table`.
* All state can be controlled or left to the component. No table library is involved; sorting
* and filtering run in memory, which suits a few thousand rows.
*/
export function DataTable<Row>({
columns,
data,
getRowId,
getRowLabel,
caption,
captionHidden = false,
selectable = false,
selected: selectedProp,
defaultSelected = [],
onSelectedChange,
selectionActions,
filterable = false,
filterPlaceholder = "Filter",
filter: filterProp,
onFilterChange,
toolbar,
sort: sortProp,
defaultSort = null,
onSortChange,
pageSize = 10,
empty,
stickyHeader,
density,
className,
tableClassName,
}: DataTableProps<Row>) {
const statusId = useId();
const [filter, setFilter] = useControllable(filterProp, "", onFilterChange);
const [sort, setSort] = useControllable<DataTableSort>(sortProp, defaultSort, onSortChange);
const [selected, setSelected] = useControllable(selectedProp, defaultSelected, onSelectedChange);
const [page, setPage] = useState(0);
const filtered = useMemo(() => {
const query = filter.trim().toLowerCase();
if (!query) return data;
const searchable = columns.filter((column) => column.filterable !== false);
return data.filter((row) =>
searchable.some((column) => {
const value = readValue(column, row);
if (column.filterable === undefined && typeof value !== "string") return false;
return value != null && String(value instanceof Date ? value.toISOString() : value).toLowerCase().includes(query);
}),
);
}, [data, columns, filter]);
const sorted = useMemo(() => {
if (!sort) return filtered;
const column = columns.find((candidate) => candidate.id === sort.id);
if (!column) return filtered;
const sign = sort.direction === "asc" ? 1 : -1;
return [...filtered].sort((a, b) => {
if (column.sortFn) return column.sortFn(a, b) * sign;
const va = readValue(column, a);
const vb = readValue(column, b);
const emptyA = va == null || va === "";
const emptyB = vb == null || vb === "";
if (emptyA || emptyB) return compare(va, vb);
return compare(va, vb) * sign;
});
}, [filtered, sort, columns]);
const paginated = pageSize > 0;
const pageCount = paginated ? Math.max(1, Math.ceil(sorted.length / pageSize)) : 1;
const currentPage = Math.min(page, pageCount - 1);
const rows = paginated ? sorted.slice(currentPage * pageSize, currentPage * pageSize + pageSize) : sorted;
// A new filter starts from the first page, so matches are never hidden on a later page.
useEffect(() => setPage(0), [filter]);
const selectedSet = useMemo(() => new Set(selected), [selected]);
const pageIds = rows.map(getRowId);
const pageSelected = pageIds.filter((id) => selectedSet.has(id)).length;
const allOnPage = pageIds.length > 0 && pageSelected === pageIds.length;
function toggleRow(id: string, checked: boolean) {
setSelected(checked ? [...selected.filter((value) => value !== id), id] : selected.filter((value) => value !== id));
}
function togglePage(checked: boolean) {
const ids = new Set(pageIds);
setSelected(checked ? [...selected.filter((id) => !ids.has(id)), ...pageIds] : selected.filter((id) => !ids.has(id)));
}
function cycleSort(id: string) {
if (sort?.id !== id) setSort({ id, direction: "asc" });
else if (sort.direction === "asc") setSort({ id, direction: "desc" });
else setSort(null);
}
const colSpan = columns.length + (selectable ? 1 : 0);
const showToolbar = filterable || toolbar || (selectable && selected.length > 0);
const first = sorted.length === 0 ? 0 : currentPage * pageSize + 1;
const last = paginated ? Math.min(sorted.length, (currentPage + 1) * pageSize) : sorted.length;
const status = filter.trim()
? `${sorted.length} ${sorted.length === 1 ? "row matches" : "rows match"}`
: `${sorted.length} ${sorted.length === 1 ? "row" : "rows"}`;
return (
<div data-slot="data-table" className={cx("grid gap-3", className)}>
{showToolbar ? (
<div className="flex min-h-9 flex-wrap items-center gap-2">
{filterable ? (
<Input
type="search"
aria-label={filterPlaceholder}
placeholder={filterPlaceholder}
value={filter}
onChange={(event) => setFilter(event.target.value)}
aria-describedby={statusId}
containerClassName="w-full sm:w-64"
className="h-8"
/>
) : null}
{selectable && selected.length > 0 ? (
<div className="flex items-center gap-2 text-sm text-zinc-600 dark:text-zinc-400">
<span className="tabular-nums">{selected.length} selected</span>
<Button variant="ghost" size="sm" onClick={() => setSelected([])}>
Clear
</Button>
{selectionActions?.(selected)}
</div>
) : null}
{toolbar ? <div className="ms-auto flex items-center gap-2">{toolbar}</div> : null}
</div>
) : null}
<Table framed stickyHeader={stickyHeader} density={density} containerClassName={tableClassName}>
<TableCaption className={captionHidden ? "sr-only" : undefined}>{caption}</TableCaption>
<TableHeader>
<TableRow>
{selectable ? (
<TableHead className="w-10 pr-0">
<SelectBox
label={allOnPage ? "Deselect all rows on this page" : "Select all rows on this page"}
checked={allOnPage}
indeterminate={pageSelected > 0 && !allOnPage}
disabled={pageIds.length === 0}
onCheckedChange={togglePage}
/>
</TableHead>
) : null}
{columns.map((column) => {
const direction = sort?.id === column.id ? sort.direction : null;
return (
<TableHead
key={column.id}
numeric={column.numeric}
aria-sort={column.sortable ? (direction === "asc" ? "ascending" : direction === "desc" ? "descending" : "none") : undefined}
className={cx(column.sortable && (column.numeric ? "pr-1.5 last:pr-2.5" : "pl-1.5 first:pl-2.5"), column.headerClassName)}
>
{column.sortable ? (
<button
type="button"
onClick={() => cycleSort(column.id)}
className={cx(
"group/sort -my-1 inline-flex h-7 items-center gap-1 rounded-md px-1.5 font-medium",
column.numeric && "flex-row-reverse",
direction ? "text-zinc-950 dark:text-white" : "text-zinc-500",
"transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none",
"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
"focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-sky-500",
)}
>
{column.header}
<SortGlyph direction={direction} />
</button>
) : (
column.header
)}
</TableHead>
);
})}
</TableRow>
</TableHeader>
<TableBody>
{rows.map((row) => {
const id = getRowId(row);
const isSelected = selectedSet.has(id);
return (
<TableRow key={id} selected={selectable ? isSelected : undefined}>
{selectable ? (
<TableCell className="w-10 pr-0">
<SelectBox label={`Select ${getRowLabel ? getRowLabel(row) : id}`} checked={isSelected} onCheckedChange={(checked) => toggleRow(id, checked)} />
</TableCell>
) : null}
{columns.map((column) => {
const value = readValue(column, row);
return (
<TableCell key={column.id} numeric={column.numeric} className={cx("whitespace-nowrap", column.className)}>
{column.cell ? column.cell(row) : value instanceof Date ? value.toLocaleDateString() : value == null ? "" : String(value)}
</TableCell>
);
})}
</TableRow>
);
})}
{rows.length === 0 ? (
<TableRow className="hover:bg-transparent dark:hover:bg-transparent">
<TableCell colSpan={colSpan} className="h-40 text-center">
{data.length > 0 && filter.trim() ? (
<div className="grid justify-items-center gap-1">
<p className="text-sm font-medium">No rows match ā{filter.trim()}ā</p>
<p className="text-sm text-zinc-500">Try a shorter search, or clear the filter.</p>
<Button variant="secondary" size="sm" className="mt-2" onClick={() => setFilter("")}>
Clear filter
</Button>
</div>
) : (
(empty ?? <p className="text-sm text-zinc-500">No rows yet.</p>)
)}
</TableCell>
</TableRow>
) : null}
</TableBody>
</Table>
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-zinc-500">
<p id={statusId} aria-live="polite" className="tabular-nums">
{paginated && sorted.length > pageSize ? `${first} to ${last} of ${sorted.length}` : status}
</p>
{paginated && pageCount > 1 ? (
<nav aria-label="Pagination" className="flex items-center gap-1">
<span className="me-2 tabular-nums">
Page {currentPage + 1} of {pageCount}
</span>
<Button
variant="secondary"
size="sm"
className="size-8 px-0"
aria-label="Previous page"
disabled={currentPage === 0}
onClick={() => setPage(currentPage - 1)}
>
<Chevron direction="left" />
</Button>
<Button
variant="secondary"
size="sm"
className="size-8 px-0"
aria-label="Next page"
disabled={currentPage >= pageCount - 1}
onClick={() => setPage(currentPage + 1)}
>
<Chevron direction="right" />
</Button>
</nav>
) : null}
</div>
</div>
);
}
function SelectBox({
label,
checked,
indeterminate = false,
disabled,
onCheckedChange,
}: {
label: string;
checked: boolean;
indeterminate?: boolean;
disabled?: boolean;
onCheckedChange: (checked: boolean) => void;
}) {
return (
<Checkbox.Root
aria-label={label}
checked={checked}
indeterminate={indeterminate}
disabled={disabled}
onCheckedChange={(next) => onCheckedChange(next)}
className={cx(
"flex size-4 items-center justify-center rounded-[4px] border align-middle",
"border-zinc-950/25 bg-white dark:border-white/30 dark:bg-black",
"data-[checked]:border-zinc-950 data-[checked]:bg-zinc-950 data-[indeterminate]:border-zinc-950 data-[indeterminate]:bg-zinc-950",
"dark:data-[checked]:border-white dark:data-[checked]:bg-white dark:data-[indeterminate]:border-white dark:data-[indeterminate]:bg-white",
"transition-[background-color,border-color] duration-150 ease-out motion-reduce:transition-none",
"hover:border-zinc-950/45 dark:hover:border-white/50",
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
"data-[disabled]:opacity-40",
)}
>
<Checkbox.Indicator
keepMounted
className={cx(
"flex text-white dark:text-black",
"transition-[opacity,scale] duration-150 ease-out motion-reduce:transition-none",
"data-[unchecked]:opacity-0 motion-safe:data-[unchecked]:scale-75",
)}
>
<svg aria-hidden="true" viewBox="0 0 12 12" fill="none" className="size-3">
{indeterminate ? (
<path d="M3 6h6" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" />
) : (
<path d="M2.75 6.25 5 8.5l4.25-5" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" />
)}
</svg>
</Checkbox.Indicator>
</Checkbox.Root>
);
}
function SortGlyph({ direction }: { direction: SortDirection | null }) {
return (
<svg aria-hidden="true" viewBox="0 0 12 12" fill="none" className="size-3 shrink-0">
<path
d="M3.5 4.75 6 2.25l2.5 2.5"
stroke="currentColor"
strokeWidth="1.25"
strokeLinecap="round"
strokeLinejoin="round"
className={cx(
"transition-opacity duration-150 motion-reduce:transition-none",
direction === "asc" ? "opacity-100" : direction === "desc" ? "opacity-25" : "opacity-40 group-hover/sort:opacity-70",
)}
/>
<path
d="M3.5 7.25 6 9.75l2.5-2.5"
stroke="currentColor"
strokeWidth="1.25"
strokeLinecap="round"
strokeLinejoin="round"
className={cx(
"transition-opacity duration-150 motion-reduce:transition-none",
direction === "desc" ? "opacity-100" : direction === "asc" ? "opacity-25" : "opacity-40 group-hover/sort:opacity-70",
)}
/>
</svg>
);
}
function Chevron({ direction }: { direction: "left" | "right" }) {
return (
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none">
<path
d={direction === "left" ? "M10 3.5 5.5 8l4.5 4.5" : "M6 3.5 10.5 8 6 12.5"}
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
}