Table
The shadcn/ui Table with row hover polish, a lit selected state and tabular numbers — plus two animated React table blocks built with Motion: a self-contained data table with sorting, filtering, row selection and pagination whose rows glide when they reorder, and a table with expandable detail rows.
- Drop-in shadcn API
- Server Component friendly
- No table library
- aria-sort
- prefers-reduced-motion
Ruby Silvaruby@harbor.dev | succeeded | $1,290.00 | |
Noah Kimnoah@orbit.app | failed | $874.00 | |
Mia Rossimia@lumen.so | succeeded | $837.00 | |
Zoe Martinzoe@pixel.co | succeeded | $721.00 | |
Nora Jensennora@fjord.co | succeeded | $512.00 |
1 of 12 row(s) selected.
"use client";
import * as React from "react";
import { Badge } from "@/components/ui/badge";
import { DataTable, type DataTableColumn } from "@/components/dusk/table/data-table";
type Payment = {
id: string;
customer: string;
email: string;
status: "succeeded" | "processing" | "failed" | "refunded";
amount: number;
};
const payments: Payment[] = [
{ id: "pay_01", customer: "Ava Chen", email: "ava@northwind.dev", status: "succeeded", amount: 316 },
{ id: "pay_02", customer: "Liam Patel", email: "liam@acme.io", status: "processing", amount: 242 },
{ id: "pay_03", customer: "Mia Rossi", email: "mia@lumen.so", status: "succeeded", amount: 837 },
{ id: "pay_04", customer: "Noah Kim", email: "noah@orbit.app", status: "failed", amount: 874 },
{ id: "pay_05", customer: "Zoe Martin", email: "zoe@pixel.co", status: "succeeded", amount: 721 },
{ id: "pay_06", customer: "Ethan Brooks", email: "ethan@vertex.dev", status: "refunded", amount: 129 },
{ id: "pay_07", customer: "Isla Novak", email: "isla@quartz.io", status: "succeeded", amount: 455 },
{ id: "pay_08", customer: "Leo Garcia", email: "leo@ember.sh", status: "processing", amount: 98 },
{ id: "pay_09", customer: "Ruby Silva", email: "ruby@harbor.dev", status: "succeeded", amount: 1290 },
{ id: "pay_10", customer: "Kai Müller", email: "kai@nimbus.app", status: "failed", amount: 64 },
{ id: "pay_11", customer: "Nora Jensen", email: "nora@fjord.co", status: "succeeded", amount: 512 },
{ id: "pay_12", customer: "Omar Haddad", email: "omar@dune.io", status: "succeeded", amount: 388 },
];
const tone = { succeeded: "success", processing: "info", failed: "destructive", refunded: "outline" } as const;
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const columns: DataTableColumn<Payment>[] = [
{
id: "customer",
header: "Customer",
accessor: (p) => p.customer,
filterValue: (p) => `${p.customer} ${p.email}`,
cell: (p) => (
<div className="flex flex-col">
<span className="font-medium">{p.customer}</span>
<span className="text-xs text-muted-foreground">{p.email}</span>
</div>
),
},
{
id: "status",
header: "Status",
accessor: (p) => p.status,
cell: (p) => (
<Badge variant={tone[p.status]} dot className="capitalize">
{p.status}
</Badge>
),
},
{ id: "amount", header: "Amount", accessor: (p) => p.amount, cell: (p) => usd.format(p.amount), align: "right" },
];
export default function DataTableDemo() {
const [selected, setSelected] = React.useState<string[]>(["pay_03"]);
return (
<DataTable
className="max-w-2xl"
caption="Recent payments"
data={payments}
columns={columns}
getRowId={(p) => p.id}
selectable
selectedIds={selected}
onSelectionChange={setSelected}
filterPlaceholder="Filter customers, emails, statuses…"
defaultSort={{ id: "amount", direction: "desc" }}
pageSize={5}
/>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/table.json1. Copy the source into
components/ui/table.tsx.table.tsx import * as React from "react"; import { cn } from "@/lib/utils"; export interface TableProps extends React.ComponentProps<"table"> { /** Classes for the scrolling wrapper around the `<table>`. */ containerClassName?: string; } /** * DuskUI Table — a drop-in upgrade of the shadcn/ui Table. * * Same parts and data-slot attributes as shadcn (Table, TableHeader, * TableBody, TableFooter, TableRow, TableHead, TableCell, TableCaption) plus: * - A subtle row hover background; selected rows (`data-state="selected"`) * get a muted background. * - Quieter header text, tabular numbers and a tinted footer for dark UIs. * - `containerClassName` for the horizontally scrolling wrapper (e.g. a border * or a max height with a sticky header). * CSS only, so it works in Server Components. Real table semantics throughout. */ function Table({ className, containerClassName, ...props }: TableProps) { return ( <div data-slot="table-container" className={cn("relative w-full overflow-x-auto", containerClassName)} > <table data-slot="table" className={cn("w-full caption-bottom border-collapse text-sm tabular-nums", className)} {...props} /> </div> ); } /** `<thead>`. Rows inside don't get the hover highlight. */ function TableHeader({ className, ...props }: React.ComponentProps<"thead">) { return ( <thead data-slot="table-header" className={cn("[&_tr]:border-b", className)} {...props} /> ); } /** `<tbody>`. */ function TableBody({ className, ...props }: React.ComponentProps<"tbody">) { return ( <tbody data-slot="table-body" className={cn("[&_tr:last-child]:border-0", className)} {...props} /> ); } /** `<tfoot>` for totals. */ function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) { return ( <tfoot data-slot="table-footer" className={cn( "border-t bg-white/[0.025] font-medium [&>tr]:last:border-b-0", className )} {...props} /> ); } /** `<tr>`. Set `data-state="selected"` to highlight a selected row. */ function TableRow({ className, ...props }: React.ComponentProps<"tr">) { return ( <tr data-slot="table-row" className={cn( "border-b transition-colors duration-150 ease-out motion-reduce:transition-none", // Hover only applies to body rows, never to header or footer rows. "[tbody>&]:hover:bg-white/[0.03] data-[state=selected]:bg-muted", className )} {...props} /> ); } /** `<th>`. Pass `scope="col"` (or `"row"`) as usual. */ function TableHead({ className, ...props }: React.ComponentProps<"th">) { return ( <th data-slot="table-head" className={cn( "h-10 px-3 text-left align-middle text-xs font-medium tracking-wide whitespace-nowrap text-muted-foreground", "[&:has([role=checkbox])]:w-10 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]", className )} {...props} /> ); } /** `<td>`. */ function TableCell({ className, ...props }: React.ComponentProps<"td">) { return ( <td data-slot="table-cell" className={cn( "px-3 py-2.5 align-middle whitespace-nowrap", "[&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]", className )} {...props} /> ); } /** `<caption>`, shown under the table. Add `sr-only` to keep it for screen readers only. */ function TableCaption({ className, ...props }: React.ComponentProps<"caption">) { return ( <caption data-slot="table-caption" className={cn("mt-4 text-sm text-muted-foreground", className)} {...props} /> ); } export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
Adds components/ui/table.tsx with the same parts as shadcn plus containerClassName for the scrolling wrapper. CSS only — no "use client" needed.
Usage
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
export function Invoices() {
return (
<Table>
<TableHeader>
<TableRow>
<TableHead scope="col">Invoice</TableHead>
<TableHead scope="col" className="text-right">Amount</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableCell>INV-1042</TableCell>
<TableCell className="text-right">$250.00</TableCell>
</TableRow>
</TableBody>
</Table>
)
}Examples
Default
Hover a row: its background lightens slightly. Header and footer rows stay still.
| Invoice | Status | Method | Amount |
|---|---|---|---|
| INV-1042 | Paid | Credit card | $250.00 |
| INV-1043 | Pending | PayPal | $150.00 |
| INV-1044 | Unpaid | Bank transfer | $350.00 |
| INV-1045 | Paid | Credit card | $450.00 |
| INV-1046 | Paid | PayPal | $550.00 |
| Total | $1,750.00 | ||
import {
Table,
TableBody,
TableCaption,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
const invoices = [
{ id: "INV-1042", status: "Paid", method: "Credit card", amount: 250 },
{ id: "INV-1043", status: "Pending", method: "PayPal", amount: 150 },
{ id: "INV-1044", status: "Unpaid", method: "Bank transfer", amount: 350 },
{ id: "INV-1045", status: "Paid", method: "Credit card", amount: 450 },
{ id: "INV-1046", status: "Paid", method: "PayPal", amount: 550 },
] as const;
const tone = { Paid: "success", Pending: "warning", Unpaid: "outline" } as const;
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
export default function TableBasicDemo() {
const total = invoices.reduce((sum, invoice) => sum + invoice.amount, 0);
return (
<Table containerClassName="max-w-xl rounded-xl border bg-card/40">
<TableCaption className="mb-3">A list of your recent invoices.</TableCaption>
<TableHeader>
<TableRow>
<TableHead scope="col" className="w-28">Invoice</TableHead>
<TableHead scope="col">Status</TableHead>
<TableHead scope="col">Method</TableHead>
<TableHead scope="col" className="text-right">Amount</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{invoices.map((invoice) => (
<TableRow key={invoice.id}>
<TableCell className="font-medium">{invoice.id}</TableCell>
<TableCell>
<Badge variant={tone[invoice.status]} dot>
{invoice.status}
</Badge>
</TableCell>
<TableCell className="text-muted-foreground">{invoice.method}</TableCell>
<TableCell className="text-right">{usd.format(invoice.amount)}</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={3}>Total</TableCell>
<TableCell className="text-right">{usd.format(total)}</TableCell>
</TableRow>
</TableFooter>
</Table>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Data Table
Sorting, filtering, selection and pagination in one self-contained component — no TanStack Table. Click a header to cycle ascending, descending and off; the arrow flips between them. Rows that stay on screen glide to their new place, new rows fade in, and short pages pad with blank rows so the table never changes height. Pass a stable getRowId so rows can animate.
Ruby Silvaruby@harbor.dev | succeeded | $1,290.00 | |
Noah Kimnoah@orbit.app | failed | $874.00 | |
Mia Rossimia@lumen.so | succeeded | $837.00 | |
Zoe Martinzoe@pixel.co | succeeded | $721.00 | |
Nora Jensennora@fjord.co | succeeded | $512.00 |
1 of 12 row(s) selected.
"use client";
import * as React from "react";
import { Badge } from "@/components/ui/badge";
import { DataTable, type DataTableColumn } from "@/components/dusk/table/data-table";
type Payment = {
id: string;
customer: string;
email: string;
status: "succeeded" | "processing" | "failed" | "refunded";
amount: number;
};
const payments: Payment[] = [
{ id: "pay_01", customer: "Ava Chen", email: "ava@northwind.dev", status: "succeeded", amount: 316 },
{ id: "pay_02", customer: "Liam Patel", email: "liam@acme.io", status: "processing", amount: 242 },
{ id: "pay_03", customer: "Mia Rossi", email: "mia@lumen.so", status: "succeeded", amount: 837 },
{ id: "pay_04", customer: "Noah Kim", email: "noah@orbit.app", status: "failed", amount: 874 },
{ id: "pay_05", customer: "Zoe Martin", email: "zoe@pixel.co", status: "succeeded", amount: 721 },
{ id: "pay_06", customer: "Ethan Brooks", email: "ethan@vertex.dev", status: "refunded", amount: 129 },
{ id: "pay_07", customer: "Isla Novak", email: "isla@quartz.io", status: "succeeded", amount: 455 },
{ id: "pay_08", customer: "Leo Garcia", email: "leo@ember.sh", status: "processing", amount: 98 },
{ id: "pay_09", customer: "Ruby Silva", email: "ruby@harbor.dev", status: "succeeded", amount: 1290 },
{ id: "pay_10", customer: "Kai Müller", email: "kai@nimbus.app", status: "failed", amount: 64 },
{ id: "pay_11", customer: "Nora Jensen", email: "nora@fjord.co", status: "succeeded", amount: 512 },
{ id: "pay_12", customer: "Omar Haddad", email: "omar@dune.io", status: "succeeded", amount: 388 },
];
const tone = { succeeded: "success", processing: "info", failed: "destructive", refunded: "outline" } as const;
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const columns: DataTableColumn<Payment>[] = [
{
id: "customer",
header: "Customer",
accessor: (p) => p.customer,
filterValue: (p) => `${p.customer} ${p.email}`,
cell: (p) => (
<div className="flex flex-col">
<span className="font-medium">{p.customer}</span>
<span className="text-xs text-muted-foreground">{p.email}</span>
</div>
),
},
{
id: "status",
header: "Status",
accessor: (p) => p.status,
cell: (p) => (
<Badge variant={tone[p.status]} dot className="capitalize">
{p.status}
</Badge>
),
},
{ id: "amount", header: "Amount", accessor: (p) => p.amount, cell: (p) => usd.format(p.amount), align: "right" },
];
export default function DataTableDemo() {
const [selected, setSelected] = React.useState<string[]>(["pay_03"]);
return (
<DataTable
className="max-w-2xl"
caption="Recent payments"
data={payments}
columns={columns}
getRowId={(p) => p.id}
selectable
selectedIds={selected}
onSelectionChange={setSelected}
filterPlaceholder="Filter customers, emails, statuses…"
defaultSort={{ id: "amount", direction: "desc" }}
pageSize={5}
/>
);
}$ npx shadcn@latest add https://duskui.com/r/data-table.json1. Install the dependencies.
npm install motion lucide-react @radix-ui/react-checkbox2. Copy the source into
components/dusk/table/data-table.tsx.data-table.tsx "use client"; import * as React from "react"; import { ArrowUpIcon, ChevronLeftIcon, ChevronRightIcon, ChevronsUpDownIcon, SearchIcon, SearchXIcon } from "lucide-react"; import { AnimatePresence, motion, useReducedMotion, type Transition } from "motion/react"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { cn } from "@/lib/utils"; export type SortDirection = "asc" | "desc"; export interface DataTableColumn<T> { /** Unique id, used for sorting. */ id: string; header: React.ReactNode; /** The raw value, used to sort and filter. Leave it out for display-only columns. */ accessor?: (row: T) => string | number | Date | null | undefined; /** Custom cell content. Defaults to the accessor value. */ cell?: (row: T) => React.ReactNode; /** Show a sort button in the header. Defaults to true when there's an accessor. */ sortable?: boolean; /** Include this column in the text filter. Defaults to true when there's an accessor or filterValue. */ filterable?: boolean; /** Text the filter matches for this column. Defaults to the accessor value. */ filterValue?: (row: T) => string; align?: "left" | "center" | "right"; /** Classes for the header and body cells of this column. */ className?: string; } export interface DataTableProps<T> extends Omit<React.ComponentProps<"div">, "children"> { data: T[]; columns: DataTableColumn<T>[]; /** A stable id per row. Rows animate by id when they move. */ getRowId: (row: T) => string; /** Accessible name for the table. Rendered as a visually hidden caption. */ caption: string; /** Rows per page. Pass 0 to show every row. */ pageSize?: number; /** Show checkboxes to select rows. */ selectable?: boolean; /** Controlled selected row ids. */ selectedIds?: string[]; onSelectionChange?: (ids: string[]) => void; /** Show the filter input. */ filterable?: boolean; filterPlaceholder?: string; /** Initial sort. */ defaultSort?: { id: string; direction: SortDirection }; /** Shown when no row matches the filter. */ emptyMessage?: React.ReactNode; /** Extra controls on the right of the toolbar. */ toolbar?: React.ReactNode; } const rowLayout: Transition = { type: "spring", stiffness: 500, damping: 42, mass: 0.8 }; const iconSpring: Transition = { type: "spring", bounce: 0, duration: 0.2 }; function compare(a: unknown, b: unknown) { 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" }); } /** Arrow that flips between ascending and descending, over a faint "unsorted" icon. */ function SortIcon({ direction }: { direction: SortDirection | null }) { const reduceMotion = useReducedMotion() ?? false; return ( <span aria-hidden className="relative grid size-3.5 place-items-center"> <motion.span className="col-start-1 row-start-1 flex" initial={false} animate={{ opacity: direction ? 0 : 0.45, scale: direction ? 0.6 : 1 }} transition={{ duration: 0.15 }} > <ChevronsUpDownIcon className="size-3.5" /> </motion.span> <motion.span className="col-start-1 row-start-1 flex text-foreground" initial={false} animate={{ opacity: direction ? 1 : 0, rotate: direction === "desc" ? 180 : 0, y: direction ? 0 : -3, }} transition={reduceMotion ? { duration: 0 } : iconSpring} > <ArrowUpIcon className="size-3.5" /> </motion.span> </span> ); } /** A table row that can animate. TableRow forwards its ref (React 19), so Motion can measure it. */ const MotionTableRow = motion.create(TableRow); /** * A self-contained data table built on the DuskUI Table: click a header to * sort (ascending → descending → off) with an arrow that flips, type to * filter, select rows with the animated Checkbox and page through results. * Rows that stay on screen glide to their new place when the order changes * (layout animations) and new rows fade in, so you can follow what moved. * Pages pad with blank rows so the table never changes height while paging. * No table library needed. Under reduced motion rows swap instantly. */ export function DataTable<T>({ data, columns, getRowId, caption, pageSize = 5, selectable = false, selectedIds, onSelectionChange, filterable = true, filterPlaceholder = "Filter…", defaultSort, emptyMessage = "No results.", toolbar, className, ...props }: DataTableProps<T>) { const reduceMotion = useReducedMotion() ?? false; const filterId = React.useId(); const [query, setQuery] = React.useState(""); const [sort, setSort] = React.useState<{ id: string; direction: SortDirection } | null>(defaultSort ?? null); const [pageState, setPageState] = React.useState(0); const [uncontrolled, setUncontrolled] = React.useState<string[]>([]); const selected = React.useMemo(() => new Set(selectedIds ?? uncontrolled), [selectedIds, uncontrolled]); const setSelected = (next: Set<string>) => { const ids = [...next]; if (selectedIds === undefined) setUncontrolled(ids); onSelectionChange?.(ids); }; const filtered = React.useMemo(() => { const q = query.trim().toLowerCase(); if (!q) return data; const searchable = columns.filter((c) => (c.filterValue || c.accessor) && c.filterable !== false); return data.filter((row) => searchable.some((c) => { let text: string; if (c.filterValue) text = c.filterValue(row); else { const value = c.accessor!(row); text = value instanceof Date ? value.toLocaleDateString() : String(value ?? ""); } return text.toLowerCase().includes(q); }) ); }, [data, columns, query]); const sorted = React.useMemo(() => { const column = sort && columns.find((c) => c.id === sort.id); if (!sort || !column?.accessor) return filtered; const factor = sort.direction === "asc" ? 1 : -1; // Copy before sorting; ties keep their original order (Array#sort is stable). return [...filtered].sort((a, b) => factor * compare(column.accessor!(a), column.accessor!(b))); }, [filtered, sort, columns]); const size = pageSize > 0 ? pageSize : Math.max(1, sorted.length); const pageCount = Math.max(1, Math.ceil(sorted.length / size)); const page = Math.min(pageState, pageCount - 1); const rows = sorted.slice(page * size, page * size + size); const fillers = pageSize > 0 && pageCount > 1 ? size - rows.length : 0; const pageIds = rows.map(getRowId); const pageSelected = pageIds.filter((id) => selected.has(id)).length; const headerState: boolean | "indeterminate" = pageIds.length > 0 && pageSelected === pageIds.length ? true : pageSelected > 0 ? "indeterminate" : false; const toggleSort = (id: string) => { setSort((current) => { if (!current || current.id !== id) return { id, direction: "asc" }; if (current.direction === "asc") return { id, direction: "desc" }; return null; }); setPageState(0); }; const colSpan = columns.length + (selectable ? 1 : 0); return ( <div data-slot="data-table" className={cn("flex w-full flex-col gap-3", className)} {...props}> {(filterable || toolbar) && ( <div className="flex flex-wrap items-center gap-2"> {filterable && ( <div className="relative w-full max-w-xs"> <label htmlFor={filterId} className="sr-only"> {filterPlaceholder} </label> <SearchIcon aria-hidden className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" /> <Input id={filterId} type="search" value={query} onChange={(e) => { setQuery(e.target.value); setPageState(0); }} placeholder={filterPlaceholder} className="pl-9" /> </div> )} {toolbar && <div className="ml-auto flex items-center gap-2">{toolbar}</div>} </div> )} <div className="overflow-hidden rounded-xl border bg-card/40"> <Table> <caption className="sr-only">{caption}</caption> <TableHeader> <TableRow> {selectable && ( <TableHead className="pl-4"> <Checkbox checked={headerState} disabled={pageIds.length === 0} onCheckedChange={(value) => { const next = new Set(selected); for (const id of pageIds) { if (value === true) next.add(id); else next.delete(id); } setSelected(next); }} aria-label="Select all rows on this page" /> </TableHead> )} {columns.map((column) => { const sortable = column.sortable ?? Boolean(column.accessor); const direction = sort?.id === column.id ? sort.direction : null; return ( <TableHead key={column.id} scope="col" aria-sort={sortable ? (direction === "asc" ? "ascending" : direction === "desc" ? "descending" : "none") : undefined} className={cn( column.align === "right" && "text-right", column.align === "center" && "text-center", column.className )} > {sortable ? ( <button type="button" onClick={() => toggleSort(column.id)} className={cn( "-mx-2 inline-flex h-7 items-center gap-1.5 rounded-md px-2 outline-none select-none", "transition-colors duration-150 hover:bg-accent hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50", direction && "text-foreground", column.align === "right" && "flex-row-reverse" )} > {column.header} <SortIcon direction={direction} /> </button> ) : ( column.header )} </TableHead> ); })} </TableRow> </TableHeader> <TableBody> <AnimatePresence initial={false}> {rows.map((row, index) => { const id = getRowId(row); const isSelected = selected.has(id); return ( <MotionTableRow key={id} layout={reduceMotion ? false : "position"} initial={{ opacity: 0, y: reduceMotion ? 0 : 6 }} animate={{ opacity: 1, y: 0 }} // Leaving rows disappear at once, so the table never holds two pages at the same time. exit={{ opacity: 0, transition: { duration: 0 } }} transition={{ layout: rowLayout, default: { duration: 0.25, ease: "easeOut", delay: reduceMotion ? 0 : index * 0.025 }, }} data-state={isSelected ? "selected" : undefined} className="h-12" > {selectable && ( <TableCell className="pl-4"> <Checkbox checked={isSelected} onCheckedChange={(value) => { const next = new Set(selected); if (value === true) next.add(id); else next.delete(id); setSelected(next); }} aria-label={`Select row ${index + 1 + page * size}`} /> </TableCell> )} {columns.map((column) => ( <TableCell key={column.id} className={cn( column.align === "right" && "text-right", column.align === "center" && "text-center", column.className )} > {column.cell ? column.cell(row) : String(column.accessor?.(row) ?? "")} </TableCell> ))} </MotionTableRow> ); })} </AnimatePresence> {rows.length === 0 && ( <tr> <td colSpan={colSpan} className="p-0"> <motion.div role="status" initial={{ opacity: 0, y: 4 }} animate={{ opacity: 1, y: 0 }} transition={reduceMotion ? { y: { duration: 0 } } : undefined} className="flex items-center justify-center gap-2 text-muted-foreground" // Keep the height of a full page (3rem per row) so the layout doesn't jump. style={{ height: `${Math.max(1, Math.min(size, data.length)) * 3}rem` }} > <SearchXIcon aria-hidden className="size-4" /> {emptyMessage} </motion.div> </td> </tr> )} {rows.length > 0 && Array.from({ length: fillers }, (_, i) => ( <tr key={`filler-${i}`} aria-hidden className="h-12 border-0"> <td colSpan={colSpan} /> </tr> ))} </TableBody> </Table> </div> <div className="flex flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground"> <p aria-live="polite" className="tabular-nums"> {selectable ? `${selected.size} of ${data.length} row(s) selected.` : `${sorted.length} ${sorted.length === 1 ? "result" : "results"}`} </p> {pageSize > 0 && ( <div className="flex items-center gap-2"> <span className="tabular-nums" aria-live="polite"> Page {page + 1} of {pageCount} </span> <Button variant="outline" size="icon-sm" onClick={() => setPageState(page - 1)} disabled={page === 0} aria-label="Previous page" > <ChevronLeftIcon /> </Button> <Button variant="outline" size="icon-sm" onClick={() => setPageState(page + 1)} disabled={page >= pageCount - 1} aria-label="Next page" > <ChevronRightIcon /> </Button> </div> )} </div> </div> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| data | T[] | — | The rows. Required. |
| columns | DataTableColumn<T>[] | — | Column definitions: id, header, accessor, cell, sortable, filterable, filterValue, align, className. Required. |
| getRowId | (row: T) => string | — | A stable id per row, used for selection and animation. Required. |
| caption | string | — | Accessible name, rendered as a visually hidden caption. Required. |
| pageSize | number | 5 | Rows per page. 0 shows every row. |
| selectable | boolean | false | Show row checkboxes and a select-all checkbox for the page. |
| selectedIds / onSelectionChange | string[] / (ids: string[]) => void | — | Control the selection. Uncontrolled when left out. |
| filterable | boolean | true | Show the filter input. |
| filterPlaceholder | string | "Filter…" | Placeholder and label of the filter input. |
| defaultSort | { id: string; direction: "asc" | "desc" } | — | The initial sort. |
| emptyMessage | ReactNode | "No results." | Shown when nothing matches the filter. |
| toolbar | ReactNode | — | Extra controls on the right of the toolbar. |
Expandable Rows
Rows that open to reveal a detail panel — logs, line items, metadata. The chevron turns, the panel springs open from zero height and its content fades up, and the open row stays lit. Set single for accordion behavior.
| Expand | Commit | Status | Duration |
|---|---|---|---|
Add calendar month transitionsmain | Ready | 42s | |
Animate rows on sortfeat/data-table | Building | 18s | |
Defer platform label until mountfix/kbd-hydration | Error | 31s | |
| |||
"use client";
import { Badge } from "@/components/ui/badge";
import { ExpandableTable, type ExpandableColumn } from "@/components/dusk/table/expandable-table";
type Deployment = {
id: string;
branch: string;
commit: string;
status: "Ready" | "Building" | "Error";
duration: string;
steps: { name: string; time: string; ok: boolean }[];
};
const deployments: Deployment[] = [
{
id: "dpl_8f2a",
branch: "main",
commit: "Add calendar month transitions",
status: "Ready",
duration: "42s",
steps: [
{ name: "Install dependencies", time: "12s", ok: true },
{ name: "Build", time: "24s", ok: true },
{ name: "Deploy to edge", time: "6s", ok: true },
],
},
{
id: "dpl_7c91",
branch: "feat/data-table",
commit: "Animate rows on sort",
status: "Building",
duration: "18s",
steps: [
{ name: "Install dependencies", time: "11s", ok: true },
{ name: "Build", time: "7s…", ok: true },
],
},
{
id: "dpl_6b40",
branch: "fix/kbd-hydration",
commit: "Defer platform label until mount",
status: "Error",
duration: "31s",
steps: [
{ name: "Install dependencies", time: "13s", ok: true },
{ name: "Type check", time: "18s", ok: false },
],
},
];
const tone = { Ready: "success", Building: "info", Error: "destructive" } as const;
const columns: ExpandableColumn<Deployment>[] = [
{
id: "commit",
header: "Commit",
cell: (d) => (
<div className="flex flex-col">
<span className="font-medium">{d.commit}</span>
<span className="font-mono text-xs text-muted-foreground">{d.branch}</span>
</div>
),
},
{ id: "status", header: "Status", cell: (d) => <Badge variant={tone[d.status]} dot>{d.status}</Badge> },
{ id: "duration", header: "Duration", cell: (d) => d.duration, align: "right" },
];
export default function ExpandableTableDemo() {
return (
<ExpandableTable
className="max-w-2xl"
caption="Recent deployments"
data={deployments}
columns={columns}
getRowId={(d) => d.id}
defaultExpanded={["dpl_6b40"]}
getExpandLabel={(d) => `Show build steps for ${d.commit}`}
renderDetail={(d) => (
<ol className="grid gap-1.5 font-mono text-xs">
{d.steps.map((step) => (
<li key={step.name} className="flex items-center gap-2">
<span
aria-hidden
className={step.ok ? "size-1.5 rounded-full bg-primary" : "size-1.5 rounded-full bg-destructive"}
/>
<span className={step.ok ? "text-foreground/80" : "text-destructive"}>
{step.name}
<span className="sr-only">{step.ok ? " (passed)" : " (failed)"}</span>
</span>
<span className="ml-auto text-muted-foreground">{step.time}</span>
</li>
))}
</ol>
)}
/>
);
}$ npx shadcn@latest add https://duskui.com/r/expandable-table.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/table/expandable-table.tsx.expandable-table.tsx "use client"; import * as React from "react"; import { ChevronRightIcon } from "lucide-react"; import { AnimatePresence, motion, useReducedMotion, type Transition } from "motion/react"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { cn } from "@/lib/utils"; export interface ExpandableColumn<T> { id: string; header: React.ReactNode; cell: (row: T) => React.ReactNode; align?: "left" | "center" | "right"; className?: string; } export interface ExpandableTableProps<T> extends Omit<React.ComponentProps<"div">, "children"> { data: T[]; columns: ExpandableColumn<T>[]; getRowId: (row: T) => string; /** Content of the detail panel under an expanded row. */ renderDetail: (row: T) => React.ReactNode; /** Accessible name for the table, rendered as a visually hidden caption. */ caption: string; /** Only one row open at a time. */ single?: boolean; /** Row ids that start expanded. */ defaultExpanded?: string[]; /** Label for the expand buttons. Receives the row. */ getExpandLabel?: (row: T) => string; } const reveal: Transition = { type: "spring", duration: 0.4, bounce: 0 }; /** * A table whose rows open to reveal a detail panel. The chevron turns, the * panel's height springs open from zero and its content fades up, and the * open row stays highlighted. Each toggle is a real button with * `aria-expanded` and `aria-controls`. Built on the DuskUI Table; under * reduced motion panels open instantly. */ export function ExpandableTable<T>({ data, columns, getRowId, renderDetail, caption, single = false, defaultExpanded = [], getExpandLabel = () => "Show details", className, ...props }: ExpandableTableProps<T>) { const reduceMotion = useReducedMotion() ?? false; const baseId = React.useId(); const [expanded, setExpanded] = React.useState<Set<string>>(() => new Set(defaultExpanded)); const toggle = (id: string) => setExpanded((current) => { const next = new Set(single ? [] : current); if (current.has(id)) next.delete(id); else next.add(id); return next; }); const colSpan = columns.length + 1; return ( <div data-slot="expandable-table" className={cn("w-full overflow-hidden rounded-xl border bg-card/40", className)} {...props}> <Table> <caption className="sr-only">{caption}</caption> <TableHeader> <TableRow> <TableHead className="w-10 pr-0"> <span className="sr-only">Expand</span> </TableHead> {columns.map((column) => ( <TableHead key={column.id} scope="col" className={cn(column.align === "right" && "text-right", column.align === "center" && "text-center", column.className)} > {column.header} </TableHead> ))} </TableRow> </TableHeader> <TableBody> {data.map((row) => { const id = getRowId(row); const open = expanded.has(id); const panelId = `${baseId}-${id}`; return ( <React.Fragment key={id}> <TableRow data-state={open ? "selected" : undefined} className={cn(open && "border-b-transparent")} > <TableCell className="w-10 pr-0"> <button type="button" aria-expanded={open} aria-controls={open ? panelId : undefined} aria-label={getExpandLabel(row)} onClick={() => toggle(id)} className={cn( "grid size-7 place-items-center rounded-md text-muted-foreground outline-none", "transition-colors duration-150 hover:bg-accent hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50", open && "text-foreground" )} > <motion.span aria-hidden className="flex" initial={false} animate={{ rotate: open ? 90 : 0 }} transition={reduceMotion ? { duration: 0 } : { duration: 0.2, ease: "easeOut" }} > <ChevronRightIcon className="size-4" /> </motion.span> </button> </TableCell> {columns.map((column) => ( <TableCell key={column.id} className={cn(column.align === "right" && "text-right", column.align === "center" && "text-center", column.className)} > {column.cell(row)} </TableCell> ))} </TableRow> <AnimatePresence initial={false}> {open && ( <tr key="detail" id={panelId} className="border-b bg-muted/30 last:border-0"> <td colSpan={colSpan} className="p-0"> <motion.div initial={{ height: 0, opacity: 0 }} animate={{ height: "auto", opacity: 1 }} exit={{ height: 0, opacity: 0 }} transition={reduceMotion ? { duration: 0 } : reveal} className="overflow-hidden" > <motion.div initial={{ y: reduceMotion ? 0 : -6 }} animate={{ y: 0 }} exit={{ y: reduceMotion ? 0 : -6 }} transition={reduceMotion ? { duration: 0 } : reveal} className="px-4 pt-1 pb-4 pl-14 whitespace-normal" > {renderDetail(row)} </motion.div> </motion.div> </td> </tr> )} </AnimatePresence> </React.Fragment> ); })} </TableBody> </Table> </div> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| data / columns / getRowId | T[] / ExpandableColumn<T>[] / (row: T) => string | — | Rows, columns (id, header, cell, align, className) and a stable id per row. Required. |
| renderDetail | (row: T) => ReactNode | — | Content of the panel under an open row. Required. |
| caption | string | — | Accessible name, rendered as a visually hidden caption. Required. |
| single | boolean | false | Only one row open at a time. |
| defaultExpanded | string[] | [] | Row ids that start open. |
| getExpandLabel | (row: T) => string | () => "Show details" | Accessible label for each row's toggle button. |
API Reference
Same parts as shadcn/ui, each a thin wrapper around the native element with a data-slot attribute: Table, TableHeader, TableBody, TableFooter, TableRow, TableHead, TableCell and TableCaption.
| Prop | Type | Default | Description |
|---|---|---|---|
| containerClassName | string | — | Table only. Classes for the horizontally scrolling wrapper, e.g. a border or max height. |
| data-state="selected" | attribute | — | TableRow. Highlights the row and keeps its accent bar lit. |
Accessibility
- Real table markup throughout:
<table>,<thead>,<th scope="col">and a<caption>(visually hidden in the blocks) that names the table. - Sortable headers are buttons inside the
<th>, and the header carriesaria-sort(ascending, descending or none) so the current order is announced. - Every checkbox has a label ("Select all rows on this page", "Select row 3"), and the selection and page counts are polite live regions.
- Expand toggles are buttons with
aria-expandedandaria-controlspointing at the open detail row. - Under prefers-reduced-motion rows swap and panels open instantly, and the sort arrow flips without spinning.