//data
Data Table
Sortable, filterable, paginated tables with row selection, built on TanStack Table v9 and the Cnippet Table. Copy-paste ready.
// title: Showcase: search, filters, selection, sorting and pagination
"use client";
import {
columnFacetingFeature,
columnFilteringFeature,
columnVisibilityFeature,
createColumnHelper,
createFacetedRowModel,
createFacetedUniqueValues,
createFilteredRowModel,
createPaginatedRowModel,
createSortedRowModel,
filterFn_arrHas,
filterFn_includesString,
globalFilteringFeature,
rowPaginationFeature,
rowSelectionFeature,
rowSortingFeature,
sortFn_alphanumeric,
tableFeatures,
useTable,
} from "@tanstack/react-table";
import {
ArrowDownIcon,
ArrowRightIcon,
ArrowUpIcon,
CircleCheckIcon,
CircleDashedIcon,
CircleXIcon,
TimerIcon,
TriangleAlertIcon,
XIcon,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
DataTable,
DataTableColumnHeader,
DataTableFacetedFilter,
type DataTableFilterOption,
DataTablePagination,
DataTableRowCheckbox,
DataTableSearch,
DataTableSelectAll,
DataTableViewOptions,
} from "@/components/ui/data-table";
type Task = {
assignee: string;
id: string;
label: "Bug" | "Feature" | "Docs";
priority: "low" | "medium" | "high" | "urgent";
status: "todo" | "in-progress" | "done" | "canceled";
title: string;
};
const STATUSES: DataTableFilterOption[] = [
{ icon: CircleDashedIcon, label: "Todo", value: "todo" },
{ icon: TimerIcon, label: "In progress", value: "in-progress" },
{ icon: CircleCheckIcon, label: "Done", value: "done" },
{ icon: CircleXIcon, label: "Canceled", value: "canceled" },
];
const PRIORITIES: DataTableFilterOption[] = [
{ icon: ArrowDownIcon, label: "Low", value: "low" },
{ icon: ArrowRightIcon, label: "Medium", value: "medium" },
{ icon: ArrowUpIcon, label: "High", value: "high" },
{ icon: TriangleAlertIcon, label: "Urgent", value: "urgent" },
];
const TITLES = [
"Checkout fails for saved cards",
"Add CSV export to reports",
"Dashboard charts load slowly",
"Document the webhooks API",
"Rate limit webhook retries",
"Dark mode for email templates",
"Fix focus ring on dialogs",
"Bulk invite from a CSV file",
"Typo in onboarding email",
"Audit log filters by actor",
"Retry failed payouts",
"Write the migration guide",
];
const LABELS: Task["label"][] = ["Bug", "Feature", "Docs"];
const ASSIGNEES = ["Alice Park", "Ben Torres", "Celia Kim", "Dan Moss"];
// A deterministic backlog so server and client render the same rows.
const TASKS: Task[] = Array.from({ length: 36 }, (_, i) => ({
assignee: ASSIGNEES[(i * 3) % ASSIGNEES.length] ?? "Unassigned",
id: `ACM-${400 + i}`,
label: LABELS[i % LABELS.length] ?? "Bug",
priority: (PRIORITIES[(i + Math.floor(i / 4)) % PRIORITIES.length]?.value ??
"low") as Task["priority"],
status: (STATUSES[(i * 3 + Math.floor(i / 5)) % STATUSES.length]?.value ??
"todo") as Task["status"],
title: TITLES[(i * 5) % TITLES.length] ?? "Untitled",
}));
const features = tableFeatures({
columnFacetingFeature,
columnFilteringFeature,
columnVisibilityFeature,
facetedRowModel: createFacetedRowModel(),
facetedUniqueValues: createFacetedUniqueValues(),
filteredRowModel: createFilteredRowModel(),
filterFns: {
arrHas: filterFn_arrHas,
includesString: filterFn_includesString,
},
globalFilteringFeature,
paginatedRowModel: createPaginatedRowModel(),
rowPaginationFeature,
rowSelectionFeature,
rowSortingFeature,
sortedRowModel: createSortedRowModel(),
sortFns: { alphanumeric: sortFn_alphanumeric },
});
const column = createColumnHelper<typeof features, Task>();
function OptionCell({
options,
value,
}: {
options: DataTableFilterOption[];
value: string;
}) {
const option = options.find((o) => o.value === value);
if (!option) return null;
return (
<span className="flex items-center gap-2">
{option.icon && <option.icon className="size-4 text-muted-foreground" />}
{option.label}
</span>
);
}
const columns = column.columns([
column.display({
cell: ({ row }) => (
<DataTableRowCheckbox label={`Select ${row.original.id}`} row={row} />
),
enableHiding: false,
header: ({ table }) => <DataTableSelectAll table={table} />,
id: "select",
}),
column.accessor("id", {
cell: (info) => (
<span className="font-mono text-muted-foreground text-xs">
{info.getValue()}
</span>
),
enableHiding: false,
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Task" />
),
}),
column.accessor("title", {
cell: ({ row }) => (
<div className="flex max-w-80 items-center gap-2">
<Badge size="sm" variant="outline">
{row.original.label}
</Badge>
<span className="truncate font-medium">{row.original.title}</span>
</div>
),
enableHiding: false,
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Title" />
),
}),
column.accessor("status", {
cell: (info) => <OptionCell options={STATUSES} value={info.getValue()} />,
enableGlobalFilter: false,
filterFn: "arrHas",
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Status" />
),
}),
column.accessor("priority", {
cell: (info) => <OptionCell options={PRIORITIES} value={info.getValue()} />,
enableGlobalFilter: false,
filterFn: "arrHas",
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Priority" />
),
}),
column.accessor("assignee", {
cell: (info) => (
<span className="text-muted-foreground">{info.getValue()}</span>
),
header: "Assignee",
}),
]);
export default function Particle() {
const table = useTable({
columns,
data: TASKS,
features,
getRowId: (row) => row.id,
globalFilterFn: "includesString",
initialState: {
columnVisibility: { assignee: false },
pagination: { pageIndex: 0, pageSize: 8 },
},
});
const statusColumn = table.getColumn("status");
const priorityColumn = table.getColumn("priority");
const isFiltered =
table.state.columnFilters.length > 0 || Boolean(table.state.globalFilter);
return (
<div className="flex w-full flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<DataTableSearch placeholder="Filter tasks…" table={table} />
{statusColumn && (
<DataTableFacetedFilter
column={statusColumn}
options={STATUSES}
title="Status"
/>
)}
{priorityColumn && (
<DataTableFacetedFilter
column={priorityColumn}
options={PRIORITIES}
title="Priority"
/>
)}
{isFiltered && (
<Button
onClick={() => {
table.resetColumnFilters();
table.resetGlobalFilter();
}}
size="sm"
variant="ghost"
>
Reset
<XIcon aria-hidden="true" />
</Button>
)}
<DataTableViewOptions table={table} />
</div>
<div className="rounded-xl border bg-background">
<DataTable emptyMessage="No tasks match these filters." table={table} />
</div>
<DataTablePagination pageSizeOptions={[8, 16, 36]} table={table} />
</div>
);
}
Installation
pnpm dlx shadcn@latest add @cnippet/data-table
Usage
TanStack Table v9 only adds a feature's state and APIs when you register it, so start by listing the features this table uses. Keep features, columns and static data outside the component so they aren't rebuilt on every render.
import {
createColumnHelper,
createPaginatedRowModel,
createSortedRowModel,
rowPaginationFeature,
rowSortingFeature,
sortFn_alphanumeric,
tableFeatures,
useTable,
} from "@tanstack/react-table"
import {
DataTable,
DataTableColumnHeader,
DataTablePagination,
} from "@/components/ui/data-table"
type Invoice = { id: string; customer: string; amount: number }
const features = tableFeatures({
rowSortingFeature,
sortedRowModel: createSortedRowModel(),
sortFns: { alphanumeric: sortFn_alphanumeric },
rowPaginationFeature,
paginatedRowModel: createPaginatedRowModel(),
})
const column = createColumnHelper<typeof features, Invoice>()
const columns = column.columns([
column.accessor("id", { header: "Invoice" }),
column.accessor("customer", {
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Customer" />
),
}),
column.accessor("amount", { header: "Amount" }),
])
export function Invoices({ data }: { data: Invoice[] }) {
const table = useTable({ features, columns, data })
return (
<div className="flex flex-col gap-3">
<DataTable table={table} />
<DataTablePagination table={table} />
</div>
)
}Anatomy
<DataTableSearch table={table} /> {/* global filter input */}
<DataTableFacetedFilter column={column} /> {/* multi-select column filter */}
<DataTableViewOptions table={table} /> {/* show/hide columns menu */}
<DataTable table={table}> {/* <Table> with headers, rows and an empty state */}
{/* in column definitions: */}
<DataTableSelectAll table={table} /> {/* header checkbox */}
<DataTableColumnHeader column={column} /> {/* sortable header button */}
<DataTableRowCheckbox row={row} /> {/* row checkbox */}
</DataTable>
<DataTablePagination table={table} /> {/* count, rows per page, page controls */}Good to know
- Each part checks its features at compile time. For example, passing a table without
rowPaginationFeaturetoDataTablePaginationis a type error, not a runtime crash. DataTablerenders whatever the table produces: visible columns, sorted, filtered and paginated rows, and expanded sub-rows. It doesn't add any behavior on its own.- The parts subscribe to their own state slice, so they stay current even if you pass a narrow selector to
useTable, and they work with the React Compiler. - Give rows a stable id with
getRowId: (row) => row.id. Selection is keyed by row id, and the default index-based ids change when rows are sorted, filtered or removed. - Selection is separate from data. After deleting selected rows, clear it with
table.resetRowSelection(true). - For a faceted filter, set the column's
filterFn: "arrHas"and registerfilterFn_arrHas. It keeps rows whose value equals any selected option. RegistercolumnFacetingFeaturewithfacetedRowModelandfacetedUniqueValuesto show a count next to each option. - Shift-click a row checkbox to select a range.
API Reference
DataTable
Renders the table's header groups and current rows using Table. Rows that are selected get data-state="selected", and sortable headers get aria-sort.
| Prop | Type | Default | Description |
|---|---|---|---|
table | ReactTable | — | The table returned by useTable |
emptyMessage | ReactNode | "No results." | Shown in a full-width row when there are no rows |
variant | "default" | "card" | "default" | Passed to Table |
Other props go on the <table> element.
DataTableColumnHeader
A header button that cycles the column's sort and shows its direction. Renders plain text when the column can't sort. Requires rowSortingFeature.
| Prop | Type | Description |
|---|---|---|
column | Column | The column from the header context |
title | ReactNode | Header label |
DataTableSelectAll / DataTableRowCheckbox
Checkboxes for the header and for each row. The header checkbox selects every row on the current page and shows an indeterminate state when only some are selected. Requires rowSelectionFeature.
| Prop | Type | Description |
|---|---|---|
table / row | Table / Row | From the header or cell context |
label | string | Accessible label |
DataTableSearch
A search input bound to the global filter. Requires columnFilteringFeature, globalFilteringFeature and filteredRowModel, plus a globalFilterFn such as "includesString".
| Prop | Type | Default |
|---|---|---|
table | Table | — |
placeholder | string | "Search…" |
DataTableFacetedFilter
A menu of checkbox options that filters one column, with the selection shown on the trigger. Requires columnFilteringFeature and the column's filterFn: "arrHas".
| Prop | Type | Description |
|---|---|---|
column | Column | From table.getColumn(id) |
title | string | Trigger and menu label |
options | { label, value, icon? }[] | Values to filter by |
DataTableViewOptions
A menu for showing and hiding columns that allow it. Labels come from string headers, falling back to the column id. Requires columnVisibilityFeature.
DataTablePagination
Row count (or selected count when rowSelectionFeature is registered), a rows-per-page select, and first, previous, next and last page buttons. Requires rowPaginationFeature and paginatedRowModel.
| Prop | Type | Default |
|---|---|---|
table | Table | — |
pageSizeOptions | number[] | [10, 20, 50] |
Examples
Sorting
Click a header to sort; click again to reverse. The table starts sorted by issue date, newest first.
// title: Sortable invoices
"use client";
import {
createColumnHelper,
createSortedRowModel,
rowSortingFeature,
sortFn_alphanumeric,
sortFn_datetime,
tableFeatures,
useTable,
} from "@tanstack/react-table";
import { Badge } from "@/components/ui/badge";
import {
DataTable,
DataTableColumnHeader,
} from "@/components/ui/data-table";
type Invoice = {
amount: number;
customer: string;
id: string;
issued: Date;
status: "paid" | "pending" | "overdue";
};
const INVOICES: Invoice[] = [
{
amount: 1250,
customer: "Northwind",
id: "INV-1042",
issued: new Date(2026, 9, 2),
status: "paid",
},
{
amount: 480,
customer: "Globex",
id: "INV-1043",
issued: new Date(2026, 9, 5),
status: "pending",
},
{
amount: 3200,
customer: "Initech",
id: "INV-1044",
issued: new Date(2026, 8, 21),
status: "overdue",
},
{
amount: 760,
customer: "Umbrella",
id: "INV-1045",
issued: new Date(2026, 9, 9),
status: "paid",
},
{
amount: 1980,
customer: "Hooli",
id: "INV-1046",
issued: new Date(2026, 9, 11),
status: "pending",
},
];
const STATUS = {
overdue: { label: "Overdue", variant: "destructive" },
paid: { label: "Paid", variant: "success" },
pending: { label: "Pending", variant: "warning" },
} as const;
const currency = new Intl.NumberFormat("en-US", {
currency: "USD",
style: "currency",
});
const dateFormat = new Intl.DateTimeFormat("en-US", {
day: "numeric",
month: "short",
});
// Features, columns and data live at module scope so the table's models
// aren't rebuilt on every render.
const features = tableFeatures({
rowSortingFeature,
sortedRowModel: createSortedRowModel(),
sortFns: { alphanumeric: sortFn_alphanumeric, datetime: sortFn_datetime },
});
const column = createColumnHelper<typeof features, Invoice>();
const columns = column.columns([
column.accessor("id", {
cell: (info) => <span className="font-medium">{info.getValue()}</span>,
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Invoice" />
),
}),
column.accessor("customer", {
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Customer" />
),
}),
column.accessor("issued", {
cell: (info) => dateFormat.format(info.getValue()),
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Issued" />
),
sortFn: "datetime",
}),
column.accessor("status", {
cell: (info) => {
const status = STATUS[info.getValue()];
return <Badge variant={status.variant}>{status.label}</Badge>;
},
enableSorting: false,
header: "Status",
}),
column.accessor("amount", {
cell: (info) => (
<div className="text-end tabular-nums">
{currency.format(info.getValue())}
</div>
),
header: ({ column }) => (
<div className="flex justify-end">
<DataTableColumnHeader column={column} title="Amount" />
</div>
),
}),
]);
export default function Particle() {
const table = useTable({
columns,
data: INVOICES,
features,
initialState: { sorting: [{ desc: true, id: "issued" }] },
});
return (
<div className="w-full max-w-2xl rounded-xl border bg-background">
<DataTable table={table} />
</div>
);
}
Search and pagination
A global search across customer name, email and company, with page size controls. The empty message appears when nothing matches.
// title: Customer directory with search and pagination
"use client";
import {
columnFilteringFeature,
createColumnHelper,
createFilteredRowModel,
createPaginatedRowModel,
createSortedRowModel,
filterFn_includesString,
globalFilteringFeature,
rowPaginationFeature,
rowSortingFeature,
sortFn_alphanumeric,
tableFeatures,
useTable,
} from "@tanstack/react-table";
import { Badge } from "@/components/ui/badge";
import {
DataTable,
DataTableColumnHeader,
DataTablePagination,
DataTableSearch,
} from "@/components/ui/data-table";
type Customer = {
company: string;
email: string;
id: string;
mrr: number;
name: string;
plan: "Free" | "Pro" | "Team";
};
const FIRST = [
"Alice",
"Ben",
"Celia",
"Dan",
"Sofia",
"Margaret",
"Priya",
"Liam",
];
const LAST = [
"Park",
"Torres",
"Kim",
"Moss",
"Reyes",
"Welsh",
"Shah",
"Rivera",
];
const COMPANIES = [
"Northwind",
"Globex",
"Initech",
"Umbrella",
"Hooli",
"Stark",
];
const PLANS: Customer["plan"][] = ["Free", "Pro", "Team"];
// A deterministic directory so server and client render the same rows.
const CUSTOMERS: Customer[] = Array.from({ length: 24 }, (_, i) => {
const first = FIRST[i % FIRST.length] ?? "Alex";
const last = LAST[(i + Math.floor(i / 8)) % LAST.length] ?? "Lee";
const plan = PLANS[(i * 7) % PLANS.length] ?? "Free";
return {
company: COMPANIES[(i * 5) % COMPANIES.length] ?? "Acme",
email: `${first.toLowerCase()}.${last.toLowerCase()}@acme.dev`,
id: `cus_${String(i + 1).padStart(3, "0")}`,
mrr: plan === "Free" ? 0 : plan === "Pro" ? 29 + i : 99 + i * 4,
name: `${first} ${last}`,
plan,
};
});
const PLAN_VARIANT = {
Free: "outline",
Pro: "secondary",
Team: "info",
} as const;
const currency = new Intl.NumberFormat("en-US", {
currency: "USD",
maximumFractionDigits: 0,
style: "currency",
});
const features = tableFeatures({
columnFilteringFeature,
filteredRowModel: createFilteredRowModel(),
filterFns: { includesString: filterFn_includesString },
globalFilteringFeature,
paginatedRowModel: createPaginatedRowModel(),
rowPaginationFeature,
rowSortingFeature,
sortedRowModel: createSortedRowModel(),
sortFns: { alphanumeric: sortFn_alphanumeric },
});
const column = createColumnHelper<typeof features, Customer>();
const columns = column.columns([
// One accessor for name + email, so search matches either; it still sorts
// by name first.
column.accessor((row) => `${row.name} ${row.email}`, {
cell: ({ row }) => (
<div className="flex flex-col gap-1">
<span className="font-medium">{row.original.name}</span>
<span className="text-muted-foreground text-xs">
{row.original.email}
</span>
</div>
),
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Customer" />
),
id: "customer",
}),
column.accessor("company", {
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Company" />
),
}),
column.accessor("plan", {
cell: (info) => (
<Badge variant={PLAN_VARIANT[info.getValue()]}>{info.getValue()}</Badge>
),
header: "Plan",
}),
column.accessor("mrr", {
cell: (info) => (
<div className="text-end tabular-nums">
{currency.format(info.getValue())}
</div>
),
header: ({ column }) => (
<div className="flex justify-end">
<DataTableColumnHeader column={column} title="MRR" />
</div>
),
}),
]);
export default function Particle() {
const table = useTable({
columns,
data: CUSTOMERS,
features,
getRowId: (row) => row.id,
globalFilterFn: "includesString",
initialState: { pagination: { pageIndex: 0, pageSize: 5 } },
});
return (
<div className="flex w-full max-w-2xl flex-col gap-3">
<DataTableSearch placeholder="Search customers…" table={table} />
<div className="rounded-xl border bg-background">
<DataTable
emptyMessage="No customers match your search."
table={table}
/>
</div>
<DataTablePagination pageSizeOptions={[5, 10, 20]} table={table} />
</div>
);
}
Row selection
Select rows to reveal bulk actions, Shift-click to select a range, and remove the selected members. The owner's row can't be selected.
// title: Team members with row selection and bulk actions
"use client";
import {
createColumnHelper,
rowSelectionFeature,
tableFeatures,
useTable,
} from "@tanstack/react-table";
import { MailIcon, UserMinusIcon, XIcon } from "lucide-react";
import { useState } from "react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
DataTable,
DataTableRowCheckbox,
DataTableSelectAll,
} from "@/components/ui/data-table";
type Member = {
email: string;
id: string;
initials: string;
name: string;
role: "Owner" | "Admin" | "Member";
};
const MEMBERS: Member[] = [
{
email: "alice@acme.dev",
id: "u1",
initials: "AP",
name: "Alice Park",
role: "Owner",
},
{
email: "ben@acme.dev",
id: "u2",
initials: "BT",
name: "Ben Torres",
role: "Admin",
},
{
email: "celia@acme.dev",
id: "u3",
initials: "CK",
name: "Celia Kim",
role: "Member",
},
{
email: "dan@acme.dev",
id: "u4",
initials: "DM",
name: "Dan Moss",
role: "Member",
},
{
email: "sofia@acme.dev",
id: "u5",
initials: "SR",
name: "Sofia Reyes",
role: "Member",
},
{
email: "priya@acme.dev",
id: "u6",
initials: "PS",
name: "Priya Shah",
role: "Admin",
},
];
const features = tableFeatures({ rowSelectionFeature });
const column = createColumnHelper<typeof features, Member>();
const columns = column.columns([
column.display({
cell: ({ row }) => (
<DataTableRowCheckbox label={`Select ${row.original.name}`} row={row} />
),
header: ({ table }) => <DataTableSelectAll table={table} />,
id: "select",
}),
column.accessor("name", {
cell: ({ row }) => (
<div className="flex items-center gap-3">
<Avatar className="size-8">
<AvatarFallback className="text-xs">
{row.original.initials}
</AvatarFallback>
</Avatar>
<div className="flex flex-col gap-1">
<span className="font-medium">{row.original.name}</span>
<span className="text-muted-foreground text-xs">
{row.original.email}
</span>
</div>
</div>
),
header: "Member",
}),
column.accessor("role", {
cell: (info) => (
<Badge variant={info.getValue() === "Member" ? "outline" : "secondary"}>
{info.getValue()}
</Badge>
),
header: "Role",
}),
]);
export default function Particle() {
const [members, setMembers] = useState(MEMBERS);
const table = useTable({
columns,
data: members,
// The owner can't be removed, so their row isn't selectable.
enableRowSelection: (row) => row.original.role !== "Owner",
features,
getRowId: (row) => row.id,
});
const selectedIds = Object.keys(table.state.rowSelection);
const removeSelected = () => {
setMembers((prev) => prev.filter((m) => !selectedIds.includes(m.id)));
// Selection is separate state; clear it along with the rows.
table.resetRowSelection(true);
};
return (
<div className="flex w-full max-w-xl flex-col gap-3">
<div className="flex min-h-8 items-center justify-between gap-3">
{selectedIds.length > 0 ? (
<>
<span className="font-medium text-sm">
{selectedIds.length} selected
</span>
<div className="flex items-center gap-1.5">
<Button size="sm" variant="outline">
<MailIcon aria-hidden="true" />
Email
</Button>
<Button onClick={removeSelected} size="sm" variant="destructive">
<UserMinusIcon aria-hidden="true" />
Remove
</Button>
<Button
aria-label="Clear selection"
onClick={() => table.resetRowSelection(true)}
size="icon-sm"
variant="ghost"
>
<XIcon aria-hidden="true" />
</Button>
</div>
</>
) : (
<span className="text-muted-foreground text-sm">
{members.length} members · Shift-click to select a range
</span>
)}
</div>
<div className="rounded-xl border bg-background">
<DataTable
emptyMessage={
<Button
onClick={() => setMembers(MEMBERS)}
size="sm"
variant="outline"
>
Restore members
</Button>
}
table={table}
/>
</div>
</div>
);
}
Column visibility
Secondary columns start hidden; the View menu shows or hides any column that allows it.
// title: Orders with column visibility menu
"use client";
import {
columnVisibilityFeature,
createColumnHelper,
createSortedRowModel,
rowSortingFeature,
sortFn_alphanumeric,
tableFeatures,
useTable,
} from "@tanstack/react-table";
import { Badge } from "@/components/ui/badge";
import {
DataTable,
DataTableColumnHeader,
DataTableViewOptions,
} from "@/components/ui/data-table";
type Order = {
channel: "Web" | "Mobile" | "Retail";
customer: string;
id: string;
items: number;
region: string;
status: "Fulfilled" | "Processing" | "Refunded";
total: number;
};
const ORDERS: Order[] = [
{
channel: "Web",
customer: "Alice Park",
id: "#3210",
items: 3,
region: "US East",
status: "Fulfilled",
total: 182,
},
{
channel: "Mobile",
customer: "Ben Torres",
id: "#3211",
items: 1,
region: "EU West",
status: "Processing",
total: 49,
},
{
channel: "Retail",
customer: "Celia Kim",
id: "#3212",
items: 5,
region: "APAC",
status: "Fulfilled",
total: 410,
},
{
channel: "Web",
customer: "Dan Moss",
id: "#3213",
items: 2,
region: "US West",
status: "Refunded",
total: 96,
},
{
channel: "Mobile",
customer: "Sofia Reyes",
id: "#3214",
items: 4,
region: "EU West",
status: "Processing",
total: 238,
},
];
const STATUS_VARIANT = {
Fulfilled: "success",
Processing: "warning",
Refunded: "outline",
} as const;
const features = tableFeatures({
columnVisibilityFeature,
rowSortingFeature,
sortedRowModel: createSortedRowModel(),
sortFns: { alphanumeric: sortFn_alphanumeric },
});
const column = createColumnHelper<typeof features, Order>();
const columns = column.columns([
column.accessor("id", {
cell: (info) => <span className="font-medium">{info.getValue()}</span>,
enableHiding: false,
header: "Order",
}),
column.accessor("customer", {
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Customer" />
),
}),
column.accessor("channel", { header: "Channel" }),
column.accessor("region", { header: "Region" }),
column.accessor("items", {
cell: (info) => (
<div className="text-end tabular-nums">{info.getValue()}</div>
),
header: () => <div className="text-end">Items</div>,
}),
column.accessor("status", {
cell: (info) => (
<Badge variant={STATUS_VARIANT[info.getValue()]}>{info.getValue()}</Badge>
),
header: "Status",
}),
column.accessor("total", {
cell: (info) => (
<div className="text-end tabular-nums">${info.getValue()}</div>
),
header: ({ column }) => (
<div className="flex justify-end">
<DataTableColumnHeader column={column} title="Total" />
</div>
),
}),
]);
export default function Particle() {
const table = useTable({
columns,
data: ORDERS,
features,
// Secondary columns start hidden; the View menu brings them back.
initialState: { columnVisibility: { channel: false, region: false } },
});
return (
<div className="flex w-full max-w-2xl flex-col gap-3">
<div className="flex items-center justify-between gap-3">
<p className="font-medium text-sm">Recent orders</p>
<DataTableViewOptions table={table} />
</div>
<div className="rounded-xl border bg-background">
<DataTable table={table} />
</div>
</div>
);
}
Faceted filters
Filter issues by status and priority, with a live count next to each option and a Reset button when any filter is active.
// title: Issue tracker with faceted status and priority filters
"use client";
import {
columnFacetingFeature,
columnFilteringFeature,
createColumnHelper,
createFacetedRowModel,
createFacetedUniqueValues,
createFilteredRowModel,
filterFn_arrHas,
filterFn_includesString,
globalFilteringFeature,
tableFeatures,
useTable,
} from "@tanstack/react-table";
import {
ArrowDownIcon,
ArrowRightIcon,
ArrowUpIcon,
CircleCheckIcon,
CircleDashedIcon,
CircleXIcon,
TimerIcon,
TriangleAlertIcon,
XIcon,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
DataTable,
DataTableFacetedFilter,
type DataTableFilterOption,
DataTableSearch,
} from "@/components/ui/data-table";
type Issue = {
id: string;
priority: "low" | "medium" | "high" | "urgent";
status: "todo" | "in-progress" | "done" | "canceled";
title: string;
};
const ISSUES: Issue[] = [
{
id: "ACM-412",
priority: "urgent",
status: "in-progress",
title: "Checkout fails for saved cards",
},
{
id: "ACM-415",
priority: "high",
status: "todo",
title: "Dashboard charts load slowly",
},
{
id: "ACM-418",
priority: "medium",
status: "done",
title: "Add CSV export to reports",
},
{
id: "ACM-420",
priority: "low",
status: "todo",
title: "Typo in onboarding email",
},
{
id: "ACM-423",
priority: "high",
status: "in-progress",
title: "Rate limit webhook retries",
},
{
id: "ACM-427",
priority: "medium",
status: "canceled",
title: "Legacy theme migration",
},
{
id: "ACM-431",
priority: "low",
status: "done",
title: "Update footer links",
},
];
const STATUSES: DataTableFilterOption[] = [
{ icon: CircleDashedIcon, label: "Todo", value: "todo" },
{ icon: TimerIcon, label: "In progress", value: "in-progress" },
{ icon: CircleCheckIcon, label: "Done", value: "done" },
{ icon: CircleXIcon, label: "Canceled", value: "canceled" },
];
const PRIORITIES: DataTableFilterOption[] = [
{ icon: ArrowDownIcon, label: "Low", value: "low" },
{ icon: ArrowRightIcon, label: "Medium", value: "medium" },
{ icon: ArrowUpIcon, label: "High", value: "high" },
{ icon: TriangleAlertIcon, label: "Urgent", value: "urgent" },
];
const features = tableFeatures({
columnFacetingFeature,
columnFilteringFeature,
facetedRowModel: createFacetedRowModel(),
facetedUniqueValues: createFacetedUniqueValues(),
filteredRowModel: createFilteredRowModel(),
filterFns: {
arrHas: filterFn_arrHas,
includesString: filterFn_includesString,
},
globalFilteringFeature,
});
const column = createColumnHelper<typeof features, Issue>();
function OptionCell({
options,
value,
}: {
options: DataTableFilterOption[];
value: string;
}) {
const option = options.find((o) => o.value === value);
if (!option) return null;
return (
<span className="flex items-center gap-2">
{option.icon && <option.icon className="size-4 text-muted-foreground" />}
{option.label}
</span>
);
}
const columns = column.columns([
column.accessor("id", {
cell: (info) => (
<span className="font-mono text-muted-foreground text-xs">
{info.getValue()}
</span>
),
enableGlobalFilter: false,
header: "Issue",
}),
column.accessor("title", {
cell: (info) => <span className="font-medium">{info.getValue()}</span>,
header: "Title",
}),
column.accessor("status", {
cell: (info) => <OptionCell options={STATUSES} value={info.getValue()} />,
enableGlobalFilter: false,
filterFn: "arrHas",
header: "Status",
}),
column.accessor("priority", {
cell: (info) => <OptionCell options={PRIORITIES} value={info.getValue()} />,
enableGlobalFilter: false,
filterFn: "arrHas",
header: "Priority",
}),
]);
export default function Particle() {
const table = useTable({
columns,
data: ISSUES,
features,
getRowId: (row) => row.id,
globalFilterFn: "includesString",
});
const statusColumn = table.getColumn("status");
const priorityColumn = table.getColumn("priority");
const isFiltered =
table.state.columnFilters.length > 0 || Boolean(table.state.globalFilter);
return (
<div className="flex w-full max-w-2xl flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<DataTableSearch placeholder="Filter issues…" table={table} />
{statusColumn && (
<DataTableFacetedFilter
column={statusColumn}
options={STATUSES}
title="Status"
/>
)}
{priorityColumn && (
<DataTableFacetedFilter
column={priorityColumn}
options={PRIORITIES}
title="Priority"
/>
)}
{isFiltered && (
<Button
onClick={() => {
table.resetColumnFilters();
table.resetGlobalFilter();
}}
size="sm"
variant="ghost"
>
Reset
<XIcon aria-hidden="true" />
</Button>
)}
</div>
<div className="rounded-xl border bg-background">
<DataTable
emptyMessage="No issues match these filters."
table={table}
/>
</div>
</div>
);
}
Expandable rows
Nested data via getSubRows, with a toggle per parent row and expand/collapse all.
// title: Department budgets with expandable sub-rows
"use client";
import {
createColumnHelper,
createExpandedRowModel,
rowExpandingFeature,
tableFeatures,
useTable,
} from "@tanstack/react-table";
import { ChevronRightIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { DataTable } from "@/components/ui/data-table";
import { Progress } from "@/components/ui/progress";
type Budget = {
budget: number;
name: string;
spent: number;
subRows?: Budget[];
};
const BUDGETS: Budget[] = [
{
budget: 420_000,
name: "Engineering",
spent: 318_000,
subRows: [
{ budget: 180_000, name: "Platform", spent: 152_000 },
{ budget: 140_000, name: "Web", spent: 96_000 },
{ budget: 100_000, name: "Mobile", spent: 70_000 },
],
},
{
budget: 160_000,
name: "Marketing",
spent: 141_000,
subRows: [
{ budget: 90_000, name: "Campaigns", spent: 88_500 },
{ budget: 70_000, name: "Events", spent: 52_500 },
],
},
{
budget: 95_000,
name: "Design",
spent: 61_000,
subRows: [
{ budget: 55_000, name: "Product design", spent: 38_000 },
{ budget: 40_000, name: "Brand", spent: 23_000 },
],
},
];
const currency = new Intl.NumberFormat("en-US", {
currency: "USD",
maximumFractionDigits: 0,
notation: "compact",
style: "currency",
});
const features = tableFeatures({
expandedRowModel: createExpandedRowModel(),
rowExpandingFeature,
});
const column = createColumnHelper<typeof features, Budget>();
const columns = column.columns([
column.accessor("name", {
cell: ({ row, getValue }) => (
<div
className="flex items-center gap-1.5"
// Indent sub-rows under their parent team.
style={{ paddingInlineStart: `${row.depth * 1.75}rem` }}
>
{row.getCanExpand() ? (
<Button
aria-expanded={row.getIsExpanded()}
aria-label={`${row.getIsExpanded() ? "Collapse" : "Expand"} ${getValue()}`}
className="-ms-1.5"
onClick={row.getToggleExpandedHandler()}
size="icon-xs"
variant="ghost"
>
<ChevronRightIcon
aria-hidden="true"
className={cn(
"transition-transform",
row.getIsExpanded() && "rotate-90",
)}
/>
</Button>
) : null}
<span className={cn(row.depth === 0 && "font-medium")}>
{getValue()}
</span>
</div>
),
header: "Department",
}),
column.accessor("spent", {
cell: ({ row }) => {
const used = Math.round((row.original.spent / row.original.budget) * 100);
return (
<div className="flex min-w-36 items-center gap-3">
<Progress aria-label="Budget used" className="w-24" value={used} />
<span className="text-muted-foreground text-xs tabular-nums">
{used}%
</span>
</div>
);
},
header: "Used",
}),
column.accessor("budget", {
cell: ({ row }) => (
<div className="text-end tabular-nums">
{currency.format(row.original.spent)}
<span className="text-muted-foreground">
{" "}
/ {currency.format(row.original.budget)}
</span>
</div>
),
header: () => <div className="text-end">Spent</div>,
}),
]);
export default function Particle() {
const table = useTable({
columns,
data: BUDGETS,
features,
getSubRows: (row) => row.subRows,
initialState: { expanded: { "0": true } },
});
return (
<div className="flex w-full max-w-2xl flex-col gap-3">
<div className="flex items-center justify-between gap-3">
<p className="font-medium text-sm">FY26 budget</p>
<div className="flex gap-1">
<Button
onClick={() => table.toggleAllRowsExpanded(true)}
size="xs"
variant="ghost"
>
Expand all
</Button>
<Button
onClick={() => table.toggleAllRowsExpanded(false)}
size="xs"
variant="ghost"
>
Collapse all
</Button>
</div>
</div>
<div className="rounded-xl border bg-background">
<DataTable table={table} />
</div>
</div>
);
}
Row actions
A card-style table with a menu of actions on each row. The actions update component state through the table's meta option.
// title: API keys card table with row actions
"use client";
import {
createColumnHelper,
tableFeatures,
useTable,
} from "@tanstack/react-table";
import { CopyIcon, EllipsisIcon, RefreshCwIcon, TrashIcon } from "lucide-react";
import { useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DataTable } from "@/components/ui/data-table";
import {
Menu,
MenuGroup,
MenuItem,
MenuPopup,
MenuSeparator,
MenuTrigger,
} from "@/components/ui/menu";
type ApiKey = {
created: string;
id: string;
lastUsed: string;
name: string;
prefix: string;
status: "active" | "revoked";
};
const KEYS: ApiKey[] = [
{
created: "Aug 4, 2026",
id: "k1",
lastUsed: "2 min ago",
name: "Production",
prefix: "sk_live_4f2a",
status: "active",
},
{
created: "Sep 12, 2026",
id: "k2",
lastUsed: "1 hr ago",
name: "Staging",
prefix: "sk_test_9c1d",
status: "active",
},
{
created: "Oct 1, 2026",
id: "k3",
lastUsed: "Never",
name: "CI pipeline",
prefix: "sk_test_77be",
status: "active",
},
{
created: "Mar 18, 2026",
id: "k4",
lastUsed: "Jun 2, 2026",
name: "Old mobile app",
prefix: "sk_live_0a93",
status: "revoked",
},
];
// Row actions need to update data owned by the component, so they're passed
// to the table through `meta` rather than captured by module-level columns.
type Actions = { revoke: (id: string) => void };
const features = tableFeatures({});
const column = createColumnHelper<typeof features, ApiKey>();
const columns = column.columns([
column.accessor("name", {
cell: ({ row }) => (
<div className="flex flex-col gap-1">
<span className="font-medium">{row.original.name}</span>
<span className="font-mono text-muted-foreground text-xs">
{row.original.prefix}••••••••
</span>
</div>
),
header: "Key",
}),
column.accessor("status", {
cell: (info) =>
info.getValue() === "active" ? (
<Badge variant="success">Active</Badge>
) : (
<Badge variant="outline">Revoked</Badge>
),
header: "Status",
}),
column.accessor("created", { header: "Created" }),
column.accessor("lastUsed", {
cell: (info) => (
<span className="text-muted-foreground">{info.getValue()}</span>
),
header: "Last used",
}),
column.display({
cell: ({ row, table }) => {
const actions = table.options.meta as Actions | undefined;
const revoked = row.original.status === "revoked";
return (
<div className="flex justify-end">
<Menu>
<MenuTrigger
render={
<Button
aria-label={`Actions for ${row.original.name}`}
size="icon-sm"
variant="ghost"
/>
}
>
<EllipsisIcon aria-hidden="true" />
</MenuTrigger>
<MenuPopup align="end" className="min-w-40">
<MenuGroup>
<MenuItem>
<CopyIcon aria-hidden="true" />
Copy prefix
</MenuItem>
<MenuItem disabled={revoked}>
<RefreshCwIcon aria-hidden="true" />
Rotate key
</MenuItem>
</MenuGroup>
<MenuSeparator />
<MenuItem
disabled={revoked}
onClick={() => actions?.revoke(row.original.id)}
variant="destructive"
>
<TrashIcon aria-hidden="true" />
Revoke
</MenuItem>
</MenuPopup>
</Menu>
</div>
);
},
header: () => <span className="sr-only">Actions</span>,
id: "actions",
}),
]);
export default function Particle() {
const [keys, setKeys] = useState(KEYS);
const actions: Actions = {
revoke: (id) =>
setKeys((prev) =>
prev.map((k) => (k.id === id ? { ...k, status: "revoked" } : k)),
),
};
const table = useTable({
columns,
data: keys,
features,
getRowId: (row) => row.id,
meta: actions,
});
return (
<div className="w-full max-w-2xl">
<DataTable table={table} variant="card" />
</div>
);
}