Containment
Data table
Table with filtering, sorting, selection and pagination. Rows slide to their new places when you sort or filter; selected rows tint from the checkbox; a bulk action bar rises in the table's footer.
Examples and variants
Team
Filter, sort by any column, select rows and archive them.
| Ana Ruizana@studio.dev | Owner | Active | 12 | |
| Ben Okaforben@studio.dev | Editor | Active | 7 | |
| Chen Weichen@studio.dev | Editor | Active | 9 | |
| Dee Kimdee@studio.dev | Viewer | Invited | 2 | |
| Eli Novakeli@studio.dev | Editor | Active | 4 | |
| Fay Laurentfay@studio.dev | Viewer | Invited | 1 |
function DataTableTeam() {
const [rows, setRows] = useState(members)
return (
<DataTable
label="Team members"
data={rows}
columns={memberColumns}
getRowId={(m) => m.id}
pageSize={6}
selectable
filterPlaceholder="Filter people"
bulkActions={(selected, clear) => (
<Button
size="sm"
variant="ghost"
className="text-(--datatable-bar-label)"
onClick={() => {
const gone = new Set(selected.map((m) => m.id))
setRows((all) => all.filter((m) => !gone.has(m.id)))
clear()
}}
>
<ArchiveIcon /> Archive
</Button>
)}
/>
)
}Spec drawing
Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.
Install
With the CLI
The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/data-table.jsonBy hand
No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.
Install the packages it uses.
Terminalnpm install @base-ui/react class-variance-authority cn lucide-reactCopy these 8 files to the same paths in your project. Imports use the
@/alias for your project root.components/ui/button.tsxbutton
components/ui/button.tsx"use client" import { useRef, useState } from "react" import { Button as ButtonPrimitive } from "@base-ui/react/button" import { CheckIcon, XIcon } from "lucide-react" import { tokenMs } from "@/lib/motion/token-ms" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "cn" // Minimal: no strokes on controls (DESIGN.md rule 11), token sizes, token focus ring, // liquid press squash instead of shadcn's translate-y nudge. // Every visual spec reads a component token (styles/tokens/components.css, --button-*). // Sizes: sm | md | lg (default = md). Variants: primary (default) | secondary | outline | ghost | link. const filled = { primary: "bg-(--button-primary-container) text-(--button-primary-label) hover:bg-(--button-primary-container-hover) active:bg-(--button-primary-container-pressed)", secondary: "bg-(--button-secondary-container) text-(--button-secondary-label) hover:bg-(--button-secondary-container-hover) active:bg-(--button-secondary-container-pressed) aria-expanded:bg-(--button-secondary-container-hover)", } const buttonVariants = cva( "liquid-press group/button relative inline-flex shrink-0 items-center justify-center overflow-hidden rounded-(--button-corner) border-solid border-(length:--button-stroke-width) border-(--stroke-color-default) bg-clip-padding text-(length:--button-label-size) [font-weight:var(--button-label-weight)] whitespace-nowrap outline-none select-none focus-visible:shadow-(--focus-ring) disabled:pointer-events-none disabled:bg-(--button-container-disabled) disabled:text-(--button-label-disabled) disabled:shadow-none aria-invalid:shadow-(--focus-ring-invalid) [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-(--button-icon-size)", { variants: { variant: { primary: filled.primary, default: filled.primary, secondary: filled.secondary, outline: "bg-(--button-outline-container) text-(--button-secondary-label) shadow-(--button-outline-elevation) hover:bg-(--button-outline-container-hover) active:bg-(--button-outline-container-pressed) aria-expanded:bg-(--button-outline-container-hover)", ghost: "text-(--button-secondary-label) hover:bg-(--button-ghost-container-hover) active:bg-(--button-ghost-container-pressed) aria-expanded:bg-(--button-ghost-container-hover) disabled:bg-transparent", destructive: "", link: "text-(--button-link-label) underline-offset-4 hover:underline disabled:bg-transparent", }, size: { xs: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-xs) gap-(--button-gap-sm) px-(--button-padding-x-xs) text-(length:--button-label-size-sm) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)", sm: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-sm) gap-(--button-gap-sm) px-(--button-padding-x-sm) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)", md: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-md) gap-(--button-gap) px-(--button-padding-x-md) has-data-[icon=inline-end]:pe-(--button-padding-x-sm) has-data-[icon=inline-start]:ps-(--button-padding-x-sm)", default: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-md) gap-(--button-gap) px-(--button-padding-x-md) has-data-[icon=inline-end]:pe-(--button-padding-x-sm) has-data-[icon=inline-start]:ps-(--button-padding-x-sm)", lg: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-lg) gap-(--button-gap) px-(--button-padding-x-lg) has-data-[icon=inline-end]:pe-(--button-padding-x-md) has-data-[icon=inline-start]:ps-(--button-padding-x-md) [&_svg:not([class*='size-'])]:size-(--button-icon-size-lg)", icon: "size-(--icon-button-size-md) rounded-(--icon-button-corner)", "icon-xs": "size-(--button-height-xs) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)", "icon-sm": "size-(--icon-button-size-sm) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)", "icon-md": "size-(--icon-button-size-md) rounded-(--icon-button-corner)", "icon-lg": "size-(--icon-button-size-lg) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-lg)", }, tone: { neutral: "", danger: "", success: "", }, }, // tone: colour intent on any variant (component-model.md §7). destructive = tone danger. compoundVariants: [ { tone: "danger", variant: ["primary", "default", "secondary", "outline", "destructive"], className: "bg-(--button-danger-container) text-(--button-danger-label) shadow-none hover:bg-(--button-danger-container-hover) active:bg-(--button-danger-container-pressed) [--focus-ring-color:var(--color-danger)]", }, { tone: "danger", variant: ["ghost", "link"], className: "text-(--button-danger-label) hover:bg-(--button-danger-container) active:bg-(--button-danger-container-hover) [--focus-ring-color:var(--color-danger)]", }, { tone: "success", variant: ["primary", "default", "secondary", "outline"], className: "bg-(--button-success-container) text-(--button-success-label) shadow-none hover:bg-(--button-success-container-hover) active:bg-(--button-success-container-pressed)", }, ], defaultVariants: { variant: "primary", size: "md", tone: "neutral", }, } ) type Wash = { id: number; x: number; y: number } type Status = "idle" | "loading" | "success" | "error" type ButtonProps = ButtonPrimitive.Props & VariantProps<typeof buttonVariants> & { /** * The button shows its own result inside a fixed width: spinner, then a * check or a cross. Prefer this to a toast (component-model.md §5). */ status?: Status /** "hold": the click only happens after holding for --duration-fill (pointer, Space or Enter). */ confirm?: "hold" /** Screen reader text for the success and error states. */ statusLabel?: { success?: string; error?: string } /** @deprecated use status="loading" */ loading?: boolean /** @deprecated use status="success" */ success?: boolean } function Button({ className, variant = "primary", size = "md", tone = "neutral", status: statusProp, confirm, statusLabel, loading = false, success = false, children, onClick, onPointerUp, onPointerDown, onPointerLeave, onKeyDown, onKeyUp, ...props }: ButtonProps) { const status: Status = statusProp ?? (loading ? "loading" : success ? "success" : "idle") const busy = status === "loading" const [wash, setWash] = useState<Wash | null>(null) const [held, setHeld] = useState(false) const holdTimer = useRef(0) const allowClick = useRef(false) const self = useRef<HTMLElement | null>(null) const resolvedTone = variant === "destructive" ? "danger" : tone function startHold(element: HTMLElement) { if (confirm !== "hold" || busy) return self.current = element setHeld(true) window.clearTimeout(holdTimer.current) holdTimer.current = window.setTimeout(() => { setHeld(false) allowClick.current = true self.current?.click() allowClick.current = false }, tokenMs("--duration-fill", element)) } function stopHold() { if (confirm !== "hold") return setHeld(false) window.clearTimeout(holdTimer.current) } function handleClick(event: Parameters<NonNullable<ButtonProps["onClick"]>>[0]) { if (busy || (confirm === "hold" && !allowClick.current)) { event.preventDefault() return } onClick?.(event) } function handlePointerUp(event: Parameters<NonNullable<ButtonProps["onPointerUp"]>>[0]) { onPointerUp?.(event) stopHold() if (event.defaultPrevented || busy || confirm === "hold") return if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return const motion = event.currentTarget.closest<HTMLElement>("[data-motion]")?.dataset.motion if (motion === "calm" || motion === "still") return const rect = event.currentTarget.getBoundingClientRect() setWash({ id: Date.now(), x: event.clientX - rect.left, y: event.clientY - rect.top, }) } const showResult = status === "success" || status === "error" return ( <ButtonPrimitive data-slot="button" data-icon={typeof size === "string" && size.startsWith("icon") ? "" : undefined} data-tone={resolvedTone} data-status={status} data-confirm={confirm} aria-busy={busy || undefined} aria-disabled={busy || undefined} {...props} className={cn( buttonVariants({ variant, size, tone: resolvedTone, className }), status === "error" && "animate-[isotope-nudge_var(--duration-fast)_var(--ease-out)]" )} onClick={handleClick} onPointerUp={handlePointerUp} onPointerDown={(event) => { onPointerDown?.(event) if (event.button === 0) startHold(event.currentTarget) }} onPointerLeave={(event) => { onPointerLeave?.(event) stopHold() }} onKeyDown={(event) => { onKeyDown?.(event) if (confirm === "hold" && (event.key === " " || event.key === "Enter") && !event.repeat) { startHold(event.currentTarget) } }} onKeyUp={(event) => { onKeyUp?.(event) if (event.key === " " || event.key === "Enter") stopHold() }} > {confirm === "hold" ? ( <span aria-hidden data-held={held ? "" : undefined} className="hold-fill pointer-events-none absolute inset-y-0 left-0 w-full bg-current opacity-20" /> ) : null} <span className={cn( "button-label relative inline-flex items-center justify-center gap-[inherit]", (busy || showResult) && "opacity-0 blur-(--motion-blur-enter) transition-[opacity,filter] duration-(--duration-fast) ease-(--ease-out)" )} > {children} {confirm === "hold" ? <span className="sr-only">(hold to confirm)</span> : null} </span> {showResult ? ( <span className="button-success absolute inset-0 inline-flex items-center justify-center" role="status"> <span className="sr-only"> {status === "success" ? statusLabel?.success ?? "Done" : statusLabel?.error ?? "Failed"} </span> {status === "success" ? <CheckIcon aria-hidden /> : <XIcon aria-hidden />} </span> ) : null} {busy ? ( <span className="absolute inset-0 inline-flex items-center justify-center gap-inline-xs"> <span className="sr-only">Loading</span> {[0, 1, 2].map((dot) => ( <span key={dot} aria-hidden className="size-inline-xs rounded-full bg-current animate-[isotope-pulse_var(--duration-pulse)_var(--ease-out)_infinite]" style={{ animationDelay: `calc(var(--duration-stagger) * ${dot})` }} /> ))} </span> ) : null} {wash ? ( <span key={wash.id} aria-hidden onAnimationEnd={() => setWash(null)} className="pointer-events-none absolute size-[calc(var(--size-control-lg)*4)] rounded-full bg-current animate-[isotope-wash_var(--duration-settle)_var(--ease-out)_both]" style={{ left: wash.x, top: wash.y }} /> ) : null} </ButtonPrimitive> ) } export { Button, buttonVariants } export type { ButtonProps }components/ui/checkbox.tsxcheckbox
components/ui/checkbox.tsx"use client" import * as React from "react" import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox" import { cn } from "cn" type Mark = "in" | "out" | "off" function quietMotion(node: HTMLElement | null) { if (typeof window === "undefined") return true if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return true const motion = node?.closest<HTMLElement>("[data-motion]")?.dataset.motion return motion === "calm" || motion === "still" } function Checkbox({ className, indeterminate, onCheckedChange, ...props }: CheckboxPrimitive.Root.Props) { const rootRef = React.useRef<HTMLElement>(null) const [mark, setMark] = React.useState<Mark>(props.defaultChecked ? "in" : "off") return ( <CheckboxPrimitive.Root ref={rootRef} data-slot="checkbox" indeterminate={indeterminate} className={cn( "hit-target peer relative flex size-(--checkbox-size) shrink-0 items-center justify-center rounded-(--checkbox-corner) border-0 bg-(--checkbox-container) text-(--checkbox-mark) shadow-1 outline-none hover:bg-(--checkbox-container-hover) focus-visible:shadow-(--focus-ring) data-disabled:cursor-not-allowed data-disabled:bg-(--checkbox-container-disabled) data-disabled:shadow-none active:scale-(--motion-scale-press)", className )} {...props} onCheckedChange={(checked, details) => { onCheckedChange?.(checked, details) if (checked) { setMark("in") return } setMark(quietMotion(rootRef.current) ? "off" : "out") }} > <span aria-hidden className="checkbox-fill" /> {indeterminate ? ( <span aria-hidden className="checkbox-dash" /> ) : mark === "off" ? null : ( <svg viewBox="0 0 16 16" aria-hidden className={cn("relative size-icon-sm", mark === "out" && "checkbox-erase")} onAnimationEnd={() => { if (mark === "out") setMark("off") }} > <path d="M3.5 8.2 6.6 11.2 12.6 4.8" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="checkbox-draw" /> </svg> )} </CheckboxPrimitive.Root> ) } export { Checkbox }components/ui/input.tsxinput
components/ui/input.tsx"use client" import * as React from "react" import { Input as InputPrimitive } from "@base-ui/react/input" import { cn } from "cn" function Input({ className, type, placeholder, onChange, ...props }: React.ComponentProps<"input">) { const inset = className?.includes("px-0") const [filled, setFilled] = React.useState(Boolean(props.value ?? props.defaultValue)) const [leaving, setLeaving] = React.useState(false) return ( <span className={cn("relative flex min-w-0 flex-1", inset && "contents")}> <InputPrimitive type={type} data-slot="input" placeholder={placeholder} className={cn( !inset && "placeholder:text-transparent", "h-(--field-height-md) w-full min-w-0 rounded-(--field-corner) border-solid border-(length:--field-stroke-width) border-(--field-stroke-color) bg-(--field-container) hover:bg-(--field-container-hover) px-(--field-padding-x-text) py-1 text-base text-(--field-label) shadow-(--field-elevation) outline-none", "transition-[box-shadow,background-color] duration-(--duration-medium) ease-(--ease-bounce-soft)", "file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-ink-subtle", "focus-visible:bg-(--field-container-focus) focus-visible:shadow-(--field-focus-shadow)", "disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-(--field-container-disabled) disabled:text-(--field-label-disabled) disabled:shadow-none", "aria-invalid:animate-[isotope-nudge_var(--duration-fast)_var(--ease-out)] aria-invalid:shadow-(--focus-ring-invalid) md:text-sm", className )} {...props} onChange={(event) => { const next = event.target.value.length > 0 const level = event.target.closest<HTMLElement>("[data-motion]")?.dataset.motion const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches const quiet = reduced || level === "calm" || level === "still" if (!filled && next && !quiet) setLeaving(true) if (!next || quiet) setLeaving(false) setFilled(next) onChange?.(event) }} /> {placeholder && !inset && (!filled || leaving) ? ( <span aria-hidden className={cn( "pointer-events-none absolute inset-y-0 left-0 flex items-center px-4 text-sm text-ink-subtle", leaving && "input-placeholder-out" )} onAnimationEnd={() => setLeaving(false)} > {placeholder} </span> ) : null} </span> ) } export { Input }components/ui/input-group.tsxinput-group
components/ui/input-group.tsx"use client" import * as React from "react" import { LoaderCircleIcon, SearchIcon, XIcon } from "lucide-react" import { cn } from "cn" import { tokenMs } from "@/lib/motion/token-ms" import { Input } from "@/components/ui/input" function InputGroup({ className, children, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="input-group" className={cn( "flex h-(--field-height-md) items-center gap-inline-sm rounded-(--field-corner) bg-(--field-container) pr-2 ps-(--field-padding-x) shadow-(--field-elevation) transition-[background-color,box-shadow] duration-(--duration-fast) ease-(--ease-out) focus-within:bg-(--field-container-focus) focus-within:shadow-(--field-focus-shadow)", className )} {...props} > {children} </div> ) } function InputGroupInput({ className, ...props }: React.ComponentProps<typeof Input>) { return ( <Input className={cn( "h-auto flex-1 bg-transparent px-0 shadow-none focus-visible:bg-transparent focus-visible:shadow-none", className )} {...props} /> ) } function InputGroupSearch({ className, defaultValue, loading = false, onChange, ...props }: React.ComponentProps<typeof Input> & { loading?: boolean }) { const inputRef = React.useRef<HTMLInputElement>(null) const pendingTimer = React.useRef(0) const [value, setValue] = React.useState(String(defaultValue ?? "")) const [pending, setPending] = React.useState(false) const busy = loading || pending const mode = busy ? "loading" : value.length > 0 ? "clear" : "search" return ( <InputGroup className={className}> <InputGroupInput ref={inputRef} {...props} value={value} onChange={(event) => { const next = event.target.value setValue(next) onChange?.(event) if (loading || next.length === 0) { window.clearTimeout(pendingTimer.current) setPending(false) return } setPending(true) window.clearTimeout(pendingTimer.current) pendingTimer.current = window.setTimeout(() => setPending(false), tokenMs("--duration-medium")) }} /> <span className="relative size-icon-md shrink-0"> <SearchIcon aria-hidden className={cn( "icon-morph pointer-events-none absolute inset-0 m-auto size-icon-sm text-muted-foreground", mode === "search" ? "scale-100 opacity-100" : "scale-50 opacity-0" )} /> <LoaderCircleIcon aria-hidden className={cn( "icon-morph icon-spin pointer-events-none absolute inset-0 m-auto size-icon-sm text-muted-foreground", mode === "loading" ? "scale-100 opacity-100" : "scale-50 opacity-0" )} /> <button type="button" aria-label="Clear" tabIndex={mode === "clear" ? 0 : -1} className={cn( "hit-target icon-morph absolute inset-0 inline-flex items-center justify-center rounded-full text-muted-foreground outline-none focus-visible:shadow-(--focus-ring)", mode === "clear" ? "scale-100 opacity-100" : "pointer-events-none scale-50 opacity-0" )} onClick={() => { setValue("") setPending(false) inputRef.current?.focus() }} > <XIcon className="size-icon-sm" /> </button> </span> </InputGroup> ) } export { InputGroup, InputGroupInput, InputGroupSearch }components/ui/pagination.tsxpagination
components/ui/pagination.tsx"use client" import * as React from "react" import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react" import { cn } from "cn" import { Button } from "@/components/ui/button" /* Pagination: move between pages of results. The active page is a pill that slides to the new number; arrows nudge in their direction when pressed. */ function pagesFor(page: number, total: number, siblings: number): (number | "gap")[] { const range = new Set([1, total, ...Array.from({ length: siblings * 2 + 1 }, (_, i) => page - siblings + i)]) const sorted = [...range].filter((n) => n >= 1 && n <= total).sort((a, b) => a - b) const out: (number | "gap")[] = [] sorted.forEach((n, i) => { if (i > 0 && n - sorted[i - 1] > 1) out.push("gap") out.push(n) }) return out } function Pagination({ page, total, onPageChange, siblings = 1, className, }: { page: number total: number onPageChange: (page: number) => void siblings?: number className?: string }) { const listRef = React.useRef<HTMLUListElement>(null) const [pill, setPill] = React.useState<{ left: number; width: number } | null>(null) const pages = pagesFor(page, total, siblings) React.useLayoutEffect(() => { const list = listRef.current if (!list) return const read = () => { const active = list.querySelector<HTMLElement>("[aria-current=page]") if (active) setPill({ left: active.offsetLeft, width: active.offsetWidth }) } read() const observer = new ResizeObserver(read) observer.observe(list) return () => observer.disconnect() }, [page, total]) return ( <nav aria-label="Pagination" data-slot="pagination" className={className}> <ul ref={listRef} className="relative flex items-center gap-1"> {pill ? ( <span aria-hidden className="pagination-pill pointer-events-none absolute top-0 h-(--size-control-sm) rounded-(--shape-full) bg-(--surface-container)" style={{ left: pill.left, width: pill.width }} /> ) : null} <li> <Button size="icon-sm" variant="ghost" aria-label="Previous page" disabled={page <= 1} onClick={() => onPageChange(page - 1)} className="pagination-prev"> <ChevronLeftIcon /> </Button> </li> {pages.map((entry, index) => entry === "gap" ? ( <li key={`gap-${index}`} aria-hidden className="px-1 text-sm text-ink-subtle"> … </li> ) : ( <li key={entry}> <Button size="icon-sm" variant="ghost" aria-label={`Page ${entry}`} aria-current={entry === page ? "page" : undefined} onClick={() => onPageChange(entry)} className={cn("relative z-[1] tabular-nums", entry === page && "font-semibold hover:bg-transparent")} > {entry} </Button> </li> ) )} <li> <Button size="icon-sm" variant="ghost" aria-label="Next page" disabled={page >= total} onClick={() => onPageChange(page + 1)} className="pagination-next"> <ChevronRightIcon /> </Button> </li> </ul> </nav> ) } export { Pagination }components/ui/rolling-number.tsxrolling-number
components/ui/rolling-number.tsx"use client" import * as React from "react" import { cn } from "cn" /* Rolling number: a number whose digits roll to new values like an odometer. Each digit column rolls on its own spring, staggered from the right. Separators stay put. Screen readers hear the final value only. */ function RollingNumber({ value, format, locale, className, }: { value: number /** Intl.NumberFormat options (currency, compact, decimals). */ format?: Intl.NumberFormatOptions locale?: string className?: string }) { const text = new Intl.NumberFormat(locale, format).format(value) const chars = text.split("") return ( <span data-slot="rolling-number" className={cn("inline-flex tabular-nums", className)}> <span aria-hidden className="inline-flex overflow-hidden"> {chars.map((char, i) => { const fromRight = chars.length - 1 - i if (!/\d/.test(char)) { return ( <span key={`s-${fromRight}`} className="rolling-sep"> {char} </span> ) } const digit = Number(char) return ( <span key={`d-${fromRight}`} className="relative inline-block h-[1lh] overflow-hidden"> <span className="rolling-column flex flex-col" style={{ translate: `0 ${-digit}lh`, transitionDelay: `calc(var(--duration-stagger) * ${fromRight})` }} > {Array.from({ length: 10 }, (_, n) => ( <span key={n} className="h-[1lh]"> {n} </span> ))} </span> </span> ) })} </span> <span className="sr-only">{text}</span> </span> ) } export { RollingNumber }components/ui/table.tsxtable
components/ui/table.tsx"use client" import * as React from "react" import { ArrowUpIcon } from "lucide-react" import { cn } from "cn" /* Table: rows and columns of comparable data. Minimal has no borders: rows alternate between canvas and a faint tint, a hover pill follows the pointer down the table, sort arrows flip with a bounce, and new rows arrive with a short highlight. Real table markup. */ function Table({ className, children, ...props }: React.ComponentProps<"table">) { const wrapRef = React.useRef<HTMLDivElement>(null) const pillRef = React.useRef<HTMLSpanElement>(null) function track(event: React.PointerEvent<HTMLDivElement>) { const row = (event.target as HTMLElement).closest<HTMLTableRowElement>("tbody tr") const wrap = wrapRef.current const pill = pillRef.current if (!row || !wrap || !pill) return const top = row.getBoundingClientRect().top - wrap.getBoundingClientRect().top + wrap.scrollTop pill.style.top = `${top}px` pill.style.height = `${row.offsetHeight}px` pill.dataset.visible = "" } return ( <div ref={wrapRef} data-slot="table-container" className="relative w-full overflow-x-auto rounded-(--table-corner) bg-(--table-container)" onPointerOver={track} onPointerLeave={() => pillRef.current?.removeAttribute("data-visible")} > <span ref={pillRef} aria-hidden className="table-pill pointer-events-none absolute inset-x-1 rounded-(--table-row-corner) bg-(--table-row-hover)" /> <table data-slot="table" className={cn("relative w-full caption-bottom border-collapse text-sm", className)} {...props}> {children} </table> </div> ) } function TableHeader(props: React.ComponentProps<"thead">) { return <thead data-slot="table-header" {...props} /> } function TableBody({ className, ...props }: React.ComponentProps<"tbody">) { return <tbody data-slot="table-body" className={cn("[&>tr:nth-child(odd)>td]:bg-(--table-row-alt)", className)} {...props} /> } function TableRow({ className, fresh = false, ...props }: React.ComponentProps<"tr"> & { fresh?: boolean }) { return <tr data-slot="table-row" data-fresh={fresh || undefined} className={cn("table-row", className)} {...props} /> } function TableHead({ className, sort, onSort, children, ...props }: React.ComponentProps<"th"> & { sort?: "ascending" | "descending" | "none"; onSort?: () => void }) { return ( <th data-slot="table-head" scope="col" aria-sort={sort} className={cn("h-(--table-head-height) px-(--table-cell-padding-x) text-start align-middle font-mono text-caption font-normal tracking-[0.08em] text-ink-subtle uppercase", className)} {...props} > {onSort ? ( <button type="button" onClick={onSort} className="hit-target group/sort -mx-1 inline-flex items-center gap-1 rounded-(--shape-sm) px-1 uppercase outline-none hover:text-foreground focus-visible:shadow-(--focus-ring)" > {children} <ArrowUpIcon aria-hidden data-sort={sort ?? "none"} className="table-sort size-(--size-icon-sm)" /> </button> ) : ( children )} </th> ) } function TableCell({ className, ...props }: React.ComponentProps<"td">) { return <td data-slot="table-cell" className={cn("h-(--table-row-height) px-(--table-cell-padding-x) align-middle first:rounded-s-(--table-row-corner) last:rounded-e-(--table-row-corner)", className)} {...props} /> } function TableCaption({ className, ...props }: React.ComponentProps<"caption">) { return <caption data-slot="table-caption" className={cn("py-3 text-sm text-muted-foreground", className)} {...props} /> } export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell, TableCaption }components/ui/data-table.tsxdata-table
components/ui/data-table.tsx"use client" import * as React from "react" import { SearchIcon, XIcon } from "lucide-react" import { cn } from "cn" import { Button } from "@/components/ui/button" import { Checkbox } from "@/components/ui/checkbox" import { InputGroup, InputGroupInput } from "@/components/ui/input-group" import { Pagination } from "@/components/ui/pagination" import { RollingNumber } from "@/components/ui/rolling-number" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" import { motionLevel } from "@/lib/overlay" import { tokenMs } from "@/lib/motion/token-ms" /* Data table: Table with filtering, sorting, selection and pagination. Sort and filter slide rows to their new places (FLIP, up to 50 rows; calm crossfades; still is instant). Selected rows get a tint that grows from the checkbox, and a bulk action bar rises inside the table with a rolling count. */ export type DataTableColumn<T> = { id: string header: string cell: (row: T) => React.ReactNode /** Makes the column sortable. */ sortValue?: (row: T) => string | number /** Text the filter searches. Columns without it are not searched. */ filterValue?: (row: T) => string align?: "start" | "end" } function DataTable<T>({ data, columns, getRowId, pageSize = 8, selectable = false, bulkActions, filterPlaceholder = "Filter", label, className, }: { data: T[] columns: DataTableColumn<T>[] getRowId: (row: T) => string pageSize?: number selectable?: boolean /** Shown in the bar when rows are selected. `clear` empties the selection. */ bulkActions?: (selected: T[], clear: () => void) => React.ReactNode filterPlaceholder?: string label: string className?: string }) { const [query, setQuery] = React.useState("") const [sort, setSort] = React.useState<{ id: string; dir: "ascending" | "descending" } | null>(null) const [page, setPage] = React.useState(1) const [selected, setSelected] = React.useState<Set<string>>(() => new Set()) const bodyRef = React.useRef<HTMLTableSectionElement>(null) const before = React.useRef<Map<string, number> | null>(null) const [fade, setFade] = React.useState(0) const filtered = React.useMemo(() => { const q = query.trim().toLowerCase() if (!q) return data return data.filter((row) => columns.some((col) => col.filterValue?.(row).toLowerCase().includes(q))) }, [data, columns, query]) const sorted = React.useMemo(() => { const col = sort && columns.find((c) => c.id === sort.id) if (!col?.sortValue || !sort) return filtered const value = col.sortValue return [...filtered].sort((a, b) => { const x = value(a) const y = value(b) const order = typeof x === "number" && typeof y === "number" ? x - y : String(x).localeCompare(String(y)) return sort.dir === "ascending" ? order : -order }) }, [filtered, columns, sort]) const pages = Math.max(1, Math.ceil(sorted.length / pageSize)) const current = Math.min(page, pages) const rows = sorted.slice((current - 1) * pageSize, current * pageSize) const selectedRows = data.filter((row) => selected.has(getRowId(row))) const pageIds = rows.map(getRowId) const pageChecked = pageIds.filter((id) => selected.has(id)).length // Remember where rows were before a sort or filter, then slide them from there. function snapshot() { const body = bodyRef.current if (!body) return const level = motionLevel(body) if (level === "still") return if (level === "calm" || body.rows.length > 50) { setFade((n) => n + 1) return } const map = new Map<string, number>() for (const row of Array.from(body.rows)) map.set(row.dataset.rowId ?? "", row.getBoundingClientRect().top) before.current = map } React.useLayoutEffect(() => { const body = bodyRef.current const map = before.current before.current = null if (!body || !map) return for (const row of Array.from(body.rows)) { const was = map.get(row.dataset.rowId ?? "") const now = row.getBoundingClientRect().top if (was === undefined) { row.animate([{ opacity: 0 }, { opacity: 1 }], { duration: tokenMs("--duration-fast", body), easing: "ease-out" }) continue } if (Math.abs(was - now) < 1) continue row.animate([{ transform: `translateY(${was - now}px)` }, { transform: "none" }], { duration: tokenMs("--spring-snappy-duration", body), easing: getComputedStyle(body).getPropertyValue("--spring-snappy").trim() || "ease-out", }) } }) function toggle(id: string, on: boolean) { setSelected((all) => { const next = new Set(all) if (on) next.add(id) else next.delete(id) return next }) } const cols = columns.length + (selectable ? 1 : 0) return ( <div data-slot="data-table" className={cn("relative flex w-full flex-col gap-stack-sm", className)}> <InputGroup className="max-w-xs"> <SearchIcon aria-hidden className="size-(--size-icon-sm) shrink-0 text-ink-subtle" /> <InputGroupInput aria-label={`${filterPlaceholder} ${label}`} placeholder={filterPlaceholder} value={query} onChange={(event) => { snapshot() setQuery(event.target.value) setPage(1) }} /> </InputGroup> <Table aria-label={label}> <TableHeader> <TableRow> {selectable ? ( <TableHead className="w-10"> <Checkbox aria-label="Select all rows on this page" checked={pageIds.length > 0 && pageChecked === pageIds.length} indeterminate={pageChecked > 0 && pageChecked < pageIds.length} onCheckedChange={(on) => pageIds.forEach((id) => toggle(id, Boolean(on)))} /> </TableHead> ) : null} {columns.map((col) => ( <TableHead key={col.id} className={col.align === "end" ? "text-end" : undefined} sort={col.sortValue ? (sort?.id === col.id ? sort.dir : "none") : undefined} onSort={ col.sortValue ? () => { snapshot() setSort((s) => s?.id !== col.id ? { id: col.id, dir: "ascending" } : s.dir === "ascending" ? { id: col.id, dir: "descending" } : null ) } : undefined } > {col.header} </TableHead> ))} </TableRow> </TableHeader> <TableBody ref={bodyRef} key={fade} className={fade ? "data-table-fade" : undefined}> {rows.length === 0 ? ( <TableRow> <TableCell colSpan={cols} className="text-center text-muted-foreground"> No results for “{query}” </TableCell> </TableRow> ) : ( rows.map((row) => { const id = getRowId(row) const on = selected.has(id) return ( <TableRow key={id} data-row-id={id} data-selected={on || undefined} aria-selected={selectable ? on : undefined}> {selectable ? ( <TableCell className="data-table-cell" style={{ "--i": 0 } as React.CSSProperties}> <Checkbox aria-label={`Select row ${id}`} checked={on} onCheckedChange={(value) => toggle(id, Boolean(value))} /> </TableCell> ) : null} {columns.map((col, index) => ( <TableCell key={col.id} className={cn("data-table-cell", col.align === "end" && "text-end tabular-nums")} style={{ "--i": index + 1 } as React.CSSProperties} > {col.cell(row)} </TableCell> ))} </TableRow> ) }) )} </TableBody> </Table> <div className="relative flex min-h-(--size-control-md) flex-wrap items-center justify-between gap-2 text-sm text-muted-foreground"> <span className="data-table-count" data-hidden={selected.size > 0 || undefined}> {sorted.length} {sorted.length === 1 ? "row" : "rows"} </span> {pages > 1 ? <Pagination page={current} total={pages} onPageChange={setPage} /> : null} {selectable ? ( <div role="region" aria-label="Bulk actions" data-visible={selected.size > 0 || undefined} inert={selected.size === 0} className="data-table-bar absolute inset-y-0 start-0 z-[2] my-auto flex h-fit w-max max-w-full items-center gap-inline-md rounded-(--datatable-bar-corner) bg-(--datatable-bar-container) py-1.5 ps-4 pe-1.5 text-sm text-(--datatable-bar-label) shadow-(--datatable-bar-elevation)" > <span className="tabular-nums"> <RollingNumber value={selected.size} /> selected </span> {bulkActions?.(selectedRows, () => setSelected(new Set()))} <Button size="icon-sm" variant="ghost" aria-label="Clear selection" className="text-(--datatable-bar-label)" onClick={() => setSelected(new Set())}> <XIcon /> </Button> </div> ) : null} </div> <span className="sr-only" aria-live="polite"> {selectable ? `${selected.size} ${selected.size === 1 ? "row" : "rows"} selected` : ""} </span> </div> ) } export { DataTable }
Imports
What the examples on this page import:
import { ArchiveIcon } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Chart } from "@/components/ui/chart"
import { DataTable, type DataTableColumn } from "@/components/ui/data-table"
import { InputOTP } from "@/components/ui/input-otp"
import { tokenMs } from "@/lib/motion/token-ms"Anatomy
- 1Filter · Input with a search icon; searches columns with filterValue.
- 2Table · The Table component (--table- tokens).
- 3Selected row · --datatable-selected grows from the checkbox.
- 4Bulk bar · --datatable-bar-container, --datatable-bar-label, --datatable-bar-corner, --datatable-bar-elevation; sits in the footer beside the pagination.
- 5Footer · Row count and Pagination.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
data, columns, getRowId | T[], DataTableColumn<T>[], (row) => string | — | Rows and columns. |
columns[].sortValue | (row) => string | number | — | Makes a column sortable. |
columns[].filterValue | (row) => string | — | Text the filter searches. |
columns[].align | "start" | "end" | "start" | End-align numbers. |
selectable | boolean | false | Adds checkboxes and the bulk bar. |
bulkActions | (selected, clear) => ReactNode | — | Buttons in the bulk bar. |
pageSize | number | 8 | Rows per page. |
label | string | — | Accessible name. |
Tokens
Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.
| Token | Points to | Light | Dark |
|---|---|---|---|
--datatable-selected | var(--color-bg-selected) | color-mix(in oklch, var(--ref-select) 12%, transparent) | color-mix(in oklch, var(--ref-select) 16%, transparent) |
--datatable-bar-container | var(--surface-inverse) | oklch(0.22 0.01 260) | oklch(0.95 0 0) |
--datatable-bar-label | var(--on-surface-inverse) | oklch(0.98 0.004 95) | oklch(0.14 0 0) |
--datatable-bar-corner | var(--shape-full) | 999px | same |
--datatable-bar-elevation | var(--elevation-3) | 0 1px 1px -0.5px oklch(0.22 0.01 260 / 8%), 0 3px 3px -1.5px oklch(0.22 0.01 260 / 8%), 0 6px 6px -3px oklch(0.22 0.01 260 / 8%), 0 12px 12px -6px oklch(0.22 0.01 260 / 8%), 0 24px 24px -12px oklch(0.22 0.01 260 / 8%), 0 48px 48px -24px oklch(0.22 0.01 260 / 6%) | 0 8px 20px oklch(0 0 0 / 45%), 0 20px 44px oklch(0 0 0 / 40%) |
Motion
| Trigger | What happens | Tokens |
|---|---|---|
| Sort / filter | Rows slide to their new places (FLIP, up to 50 rows). Calm crossfades. | --spring-snappy |
| Select | The tint grows cell by cell from the checkbox. | --duration-medium, --duration-stagger |
| Bulk bar | Rises with a bounce; the count rolls. | --spring-bouncy |
Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.
Accessibility
- aria-sort on sortable headers; header checkbox is indeterminate for part of a page.
- "3 rows selected" is announced.
- The bulk bar is a labelled region and inert while hidden.
Usage
Do
- Use for lists people manage: members, orders, files.
Don’t
- Don't use for a handful of rows (use Table).
Code
"use client"
import * as React from "react"
import { SearchIcon, XIcon } from "lucide-react"
import { cn } from "cn"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { InputGroup, InputGroupInput } from "@/components/ui/input-group"
import { Pagination } from "@/components/ui/pagination"
import { RollingNumber } from "@/components/ui/rolling-number"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { motionLevel } from "@/lib/overlay"
import { tokenMs } from "@/lib/motion/token-ms"
/*
Data table: Table with filtering, sorting, selection and pagination.
Sort and filter slide rows to their new places (FLIP, up to 50 rows; calm
crossfades; still is instant). Selected rows get a tint that grows from the
checkbox, and a bulk action bar rises inside the table with a rolling count.
*/
export type DataTableColumn<T> = {
id: string
header: string
cell: (row: T) => React.ReactNode
/** Makes the column sortable. */
sortValue?: (row: T) => string | number
/** Text the filter searches. Columns without it are not searched. */
filterValue?: (row: T) => string
align?: "start" | "end"
}
function DataTable<T>({
data,
columns,
getRowId,
pageSize = 8,
selectable = false,
bulkActions,
filterPlaceholder = "Filter",
label,
className,
}: {
data: T[]
columns: DataTableColumn<T>[]
getRowId: (row: T) => string
pageSize?: number
selectable?: boolean
/** Shown in the bar when rows are selected. `clear` empties the selection. */
bulkActions?: (selected: T[], clear: () => void) => React.ReactNode
filterPlaceholder?: string
label: string
className?: string
}) {
const [query, setQuery] = React.useState("")
const [sort, setSort] = React.useState<{ id: string; dir: "ascending" | "descending" } | null>(null)
const [page, setPage] = React.useState(1)
const [selected, setSelected] = React.useState<Set<string>>(() => new Set())
const bodyRef = React.useRef<HTMLTableSectionElement>(null)
const before = React.useRef<Map<string, number> | null>(null)
const [fade, setFade] = React.useState(0)
const filtered = React.useMemo(() => {
const q = query.trim().toLowerCase()
if (!q) return data
return data.filter((row) => columns.some((col) => col.filterValue?.(row).toLowerCase().includes(q)))
}, [data, columns, query])
const sorted = React.useMemo(() => {
const col = sort && columns.find((c) => c.id === sort.id)
if (!col?.sortValue || !sort) return filtered
const value = col.sortValue
return [...filtered].sort((a, b) => {
const x = value(a)
const y = value(b)
const order = typeof x === "number" && typeof y === "number" ? x - y : String(x).localeCompare(String(y))
return sort.dir === "ascending" ? order : -order
})
}, [filtered, columns, sort])
const pages = Math.max(1, Math.ceil(sorted.length / pageSize))
const current = Math.min(page, pages)
const rows = sorted.slice((current - 1) * pageSize, current * pageSize)
const selectedRows = data.filter((row) => selected.has(getRowId(row)))
const pageIds = rows.map(getRowId)
const pageChecked = pageIds.filter((id) => selected.has(id)).length
// Remember where rows were before a sort or filter, then slide them from there.
function snapshot() {
const body = bodyRef.current
if (!body) return
const level = motionLevel(body)
if (level === "still") return
if (level === "calm" || body.rows.length > 50) {
setFade((n) => n + 1)
return
}
const map = new Map<string, number>()
for (const row of Array.from(body.rows)) map.set(row.dataset.rowId ?? "", row.getBoundingClientRect().top)
before.current = map
}
React.useLayoutEffect(() => {
const body = bodyRef.current
const map = before.current
before.current = null
if (!body || !map) return
for (const row of Array.from(body.rows)) {
const was = map.get(row.dataset.rowId ?? "")
const now = row.getBoundingClientRect().top
if (was === undefined) {
row.animate([{ opacity: 0 }, { opacity: 1 }], { duration: tokenMs("--duration-fast", body), easing: "ease-out" })
continue
}
if (Math.abs(was - now) < 1) continue
row.animate([{ transform: `translateY(${was - now}px)` }, { transform: "none" }], {
duration: tokenMs("--spring-snappy-duration", body),
easing: getComputedStyle(body).getPropertyValue("--spring-snappy").trim() || "ease-out",
})
}
})
function toggle(id: string, on: boolean) {
setSelected((all) => {
const next = new Set(all)
if (on) next.add(id)
else next.delete(id)
return next
})
}
const cols = columns.length + (selectable ? 1 : 0)
return (
<div data-slot="data-table" className={cn("relative flex w-full flex-col gap-stack-sm", className)}>
<InputGroup className="max-w-xs">
<SearchIcon aria-hidden className="size-(--size-icon-sm) shrink-0 text-ink-subtle" />
<InputGroupInput
aria-label={`${filterPlaceholder} ${label}`}
placeholder={filterPlaceholder}
value={query}
onChange={(event) => {
snapshot()
setQuery(event.target.value)
setPage(1)
}}
/>
</InputGroup>
<Table aria-label={label}>
<TableHeader>
<TableRow>
{selectable ? (
<TableHead className="w-10">
<Checkbox
aria-label="Select all rows on this page"
checked={pageIds.length > 0 && pageChecked === pageIds.length}
indeterminate={pageChecked > 0 && pageChecked < pageIds.length}
onCheckedChange={(on) => pageIds.forEach((id) => toggle(id, Boolean(on)))}
/>
</TableHead>
) : null}
{columns.map((col) => (
<TableHead
key={col.id}
className={col.align === "end" ? "text-end" : undefined}
sort={col.sortValue ? (sort?.id === col.id ? sort.dir : "none") : undefined}
onSort={
col.sortValue
? () => {
snapshot()
setSort((s) =>
s?.id !== col.id ? { id: col.id, dir: "ascending" } : s.dir === "ascending" ? { id: col.id, dir: "descending" } : null
)
}
: undefined
}
>
{col.header}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody ref={bodyRef} key={fade} className={fade ? "data-table-fade" : undefined}>
{rows.length === 0 ? (
<TableRow>
<TableCell colSpan={cols} className="text-center text-muted-foreground">
No results for “{query}”
</TableCell>
</TableRow>
) : (
rows.map((row) => {
const id = getRowId(row)
const on = selected.has(id)
return (
<TableRow key={id} data-row-id={id} data-selected={on || undefined} aria-selected={selectable ? on : undefined}>
{selectable ? (
<TableCell className="data-table-cell" style={{ "--i": 0 } as React.CSSProperties}>
<Checkbox aria-label={`Select row ${id}`} checked={on} onCheckedChange={(value) => toggle(id, Boolean(value))} />
</TableCell>
) : null}
{columns.map((col, index) => (
<TableCell
key={col.id}
className={cn("data-table-cell", col.align === "end" && "text-end tabular-nums")}
style={{ "--i": index + 1 } as React.CSSProperties}
>
{col.cell(row)}
</TableCell>
))}
</TableRow>
)
})
)}
</TableBody>
</Table>
<div className="relative flex min-h-(--size-control-md) flex-wrap items-center justify-between gap-2 text-sm text-muted-foreground">
<span className="data-table-count" data-hidden={selected.size > 0 || undefined}>
{sorted.length} {sorted.length === 1 ? "row" : "rows"}
</span>
{pages > 1 ? <Pagination page={current} total={pages} onPageChange={setPage} /> : null}
{selectable ? (
<div
role="region"
aria-label="Bulk actions"
data-visible={selected.size > 0 || undefined}
inert={selected.size === 0}
className="data-table-bar absolute inset-y-0 start-0 z-[2] my-auto flex h-fit w-max max-w-full items-center gap-inline-md rounded-(--datatable-bar-corner) bg-(--datatable-bar-container) py-1.5 ps-4 pe-1.5 text-sm text-(--datatable-bar-label) shadow-(--datatable-bar-elevation)"
>
<span className="tabular-nums">
<RollingNumber value={selected.size} /> selected
</span>
{bulkActions?.(selectedRows, () => setSelected(new Set()))}
<Button size="icon-sm" variant="ghost" aria-label="Clear selection" className="text-(--datatable-bar-label)" onClick={() => setSelected(new Set())}>
<XIcon />
</Button>
</div>
) : null}
</div>
<span className="sr-only" aria-live="polite">
{selectable ? `${selected.size} ${selected.size === 1 ? "row" : "rows"} selected` : ""}
</span>
</div>
)
}
export { DataTable }