Data table
A typed table driven by column definitions. It sorts by any column (aria-sort on headers), filters by text across searchable columns and by one category shown as chips with counts, selects rows with a select-all checkbox that turns indeterminate and shift-click ranges, swaps the toolbar for your bulk actions while rows are selected, paginates with a page-size picker, and shows an empty state with a clear-filters button. Columns can hide below a breakpoint.
Source
"use client";
import * as React from "react";
import { ArrowDown, ArrowUp, ArrowUpDown, ChevronLeft, ChevronRight, Search, SearchX, X } from "lucide-react";
import { cn } from "@/lib/utils";
type Primitive = string | number | Date | null | undefined;
export interface ColumnDef<T> {
id: string;
header: string;
/** Value used for sorting and text search. */
accessor?: (row: T) => Primitive;
/** Custom cell. Falls back to the accessor's value. */
cell?: (row: T) => React.ReactNode;
sortable?: boolean;
/** Include this column in the text filter. Defaults to true when there is an accessor. */
searchable?: boolean;
align?: "left" | "right";
/** Hide the column below a breakpoint. */
hideBelow?: "sm" | "md" | "lg";
className?: string;
}
export interface DataTableFacet<T> {
label: string;
accessor: (row: T) => string;
options: { value: string; label: string }[];
}
export interface DataTableProps<T> {
data: T[];
columns: ColumnDef<T>[];
getRowId: (row: T) => string;
/** Names a row for its checkbox label, e.g. the invoice number. Defaults to the row id. */
getRowLabel?: (row: T) => string;
/** Accessible name of the table (visually hidden caption). */
caption: string;
searchPlaceholder?: string;
/** One categorical filter shown as chips with counts, e.g. status. */
facet?: DataTableFacet<T>;
selectable?: boolean;
onSelectionChange?: (ids: string[]) => void;
/** Shown in the toolbar while rows are selected. */
bulkActions?: (selected: T[], clear: () => void) => React.ReactNode;
/** Shown in the toolbar while nothing is selected. */
toolbar?: React.ReactNode;
initialSort?: { id: string; direction: "asc" | "desc" };
pageSize?: number;
pageSizes?: number[];
/** Shown when there is no data at all (not when filters hide everything). */
emptyState?: React.ReactNode;
className?: string;
}
const HIDE: Record<NonNullable<ColumnDef<unknown>["hideBelow"]>, string> = {
sm: "hidden sm:table-cell",
md: "hidden md:table-cell",
lg: "hidden lg:table-cell",
};
const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-ring";
const checkbox = "size-4 cursor-pointer rounded border-input accent-primary align-middle dark:[color-scheme:dark]";
function compare(a: Primitive, b: Primitive) {
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" });
}
function display(value: Primitive) {
if (value instanceof Date) return value.toLocaleDateString();
return value ?? "";
}
function Checkbox({ checked, indeterminate = false, ...props }: React.InputHTMLAttributes<HTMLInputElement> & { indeterminate?: boolean }) {
const ref = React.useRef<HTMLInputElement>(null);
React.useEffect(() => {
if (ref.current) ref.current.indeterminate = indeterminate;
}, [indeterminate]);
return <input ref={ref} type="checkbox" checked={checked} className={checkbox} {...props} />;
}
export function DataTable<T>({
data,
columns,
getRowId,
getRowLabel,
caption,
searchPlaceholder = "Filter",
facet,
selectable = false,
onSelectionChange,
bulkActions,
toolbar,
initialSort,
pageSize: initialPageSize = 10,
pageSizes = [10, 20, 50],
emptyState,
className,
}: DataTableProps<T>) {
const [query, setQuery] = React.useState("");
const [facetValue, setFacetValue] = React.useState<string | null>(null);
const [sort, setSort] = React.useState(initialSort ?? null);
const [page, setPage] = React.useState(0);
const [pageSize, setPageSize] = React.useState(initialPageSize);
const [selected, setSelected] = React.useState<Set<string>>(() => new Set());
const anchor = React.useRef<number | null>(null);
const searchId = React.useId();
const searched = React.useMemo(() => {
const needle = query.trim().toLowerCase();
if (!needle) return data;
const searchable = columns.filter((column) => column.accessor && column.searchable !== false);
return data.filter((row) => searchable.some((column) => String(display(column.accessor!(row))).toLowerCase().includes(needle)));
}, [data, columns, query]);
const filtered = React.useMemo(
() => (facet && facetValue ? searched.filter((row) => facet.accessor(row) === facetValue) : searched),
[searched, facet, facetValue],
);
const sorted = React.useMemo(() => {
const column = sort && columns.find((item) => item.id === sort.id);
if (!column?.accessor) return filtered;
const factor = sort!.direction === "asc" ? 1 : -1;
return [...filtered].sort((a, b) => compare(column.accessor!(a), column.accessor!(b)) * factor);
}, [filtered, sort, columns]);
const pageCount = Math.max(1, Math.ceil(sorted.length / pageSize));
const current = Math.min(page, pageCount - 1);
const rows = sorted.slice(current * pageSize, current * pageSize + pageSize);
const rowIds = rows.map(getRowId);
const selectedOnPage = rowIds.filter((id) => selected.has(id)).length;
const allOnPage = rows.length > 0 && selectedOnPage === rows.length;
const filtersActive = query.trim() !== "" || facetValue !== null;
const update = (next: Set<string>) => {
setSelected(next);
onSelectionChange?.([...next]);
};
React.useEffect(() => setPage(0), [query, facetValue, pageSize]);
function toggleSort(id: string) {
setSort((value) => (value?.id !== id ? { id, direction: "asc" } : value.direction === "asc" ? { id, direction: "desc" } : null));
}
function toggleRow(index: number, shift: boolean) {
const next = new Set(selected);
const id = rowIds[index];
const on = !next.has(id);
// Shift-click selects or clears the range from the last clicked row.
const [from, to] = shift && anchor.current !== null ? [Math.min(anchor.current, index), Math.max(anchor.current, index)] : [index, index];
for (let i = from; i <= to; i++) on ? next.add(rowIds[i]) : next.delete(rowIds[i]);
anchor.current = index;
update(next);
}
function togglePage() {
const next = new Set(selected);
rowIds.forEach((id) => (allOnPage ? next.delete(id) : next.add(id)));
update(next);
}
const clearSelection = () => update(new Set());
const selectedRows = data.filter((row) => selected.has(getRowId(row)));
const facetCounts = facet
? Object.fromEntries(facet.options.map((option) => [option.value, searched.filter((row) => facet.accessor(row) === option.value).length]))
: {};
const colSpan = columns.length + (selectable ? 1 : 0);
return (
<div className={cn("w-full min-w-0", className)}>
<div className="flex flex-wrap items-center gap-3 pb-3">
<div className="relative order-1 min-w-0 flex-1 sm:max-w-64">
<label htmlFor={searchId} className="sr-only">
{searchPlaceholder}
</label>
<Search aria-hidden className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<input
id={searchId}
type="search"
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={searchPlaceholder}
className="h-9 w-full rounded-md border border-input bg-transparent pr-8 pl-8 text-sm shadow-xs outline-none transition-colors placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30 [&::-webkit-search-cancel-button]:hidden"
/>
{query && (
<button
type="button"
onClick={() => setQuery("")}
aria-label="Clear filter"
className={cn("absolute top-1/2 right-1.5 grid size-6 -translate-y-1/2 place-items-center rounded text-muted-foreground hover:text-foreground", focusRing)}
>
<X aria-hidden className="size-3.5" />
</button>
)}
</div>
{facet && (
<div role="group" aria-label={facet.label} className="order-3 -mx-1 flex basis-full gap-1 overflow-x-auto px-1 py-0.5 lg:order-2 lg:basis-auto">
{[{ value: null as string | null, label: "All", count: searched.length }, ...facet.options.map((option) => ({ ...option, count: facetCounts[option.value] }))].map(
(option) => (
<button
key={option.label}
type="button"
aria-pressed={facetValue === option.value}
onClick={() => setFacetValue(option.value)}
className={cn(
"inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full border px-3 text-sm whitespace-nowrap transition-colors",
focusRing,
facetValue === option.value
? "border-primary bg-primary text-primary-foreground"
: "bg-background text-muted-foreground hover:bg-accent hover:text-accent-foreground",
)}
>
{option.label}
<span className={cn("text-xs tabular-nums", facetValue === option.value ? "opacity-80" : "opacity-70")}>{option.count}</span>
</button>
),
)}
</div>
)}
<div className="order-2 ml-auto flex min-h-9 items-center gap-2 lg:order-3">
{selected.size > 0 && bulkActions ? bulkActions(selectedRows, clearSelection) : toolbar}
</div>
</div>
<div className="overflow-x-auto rounded-lg border">
<table className="w-full text-sm">
<caption className="sr-only">{caption}</caption>
<thead className="border-b bg-muted/40">
<tr>
{selectable && (
<th scope="col" className="w-10 py-2.5 pl-4 text-left">
<Checkbox
aria-label={allOnPage ? "Deselect all rows on this page" : "Select all rows on this page"}
checked={allOnPage}
indeterminate={selectedOnPage > 0 && !allOnPage}
onChange={togglePage}
disabled={!rows.length}
/>
</th>
)}
{columns.map((column) => {
const active = sort?.id === column.id;
const Icon = !active ? ArrowUpDown : sort!.direction === "asc" ? ArrowUp : ArrowDown;
return (
<th
key={column.id}
scope="col"
aria-sort={active ? (sort!.direction === "asc" ? "ascending" : "descending") : undefined}
className={cn(
"h-10 px-4 text-xs font-medium whitespace-nowrap text-muted-foreground",
column.align === "right" ? "text-right" : "text-left",
column.hideBelow && HIDE[column.hideBelow],
)}
>
{column.sortable && column.accessor ? (
<button
type="button"
onClick={() => toggleSort(column.id)}
className={cn(
"-mx-1.5 inline-flex items-center gap-1 rounded px-1.5 py-1 transition-colors hover:text-foreground",
focusRing,
column.align === "right" && "flex-row-reverse",
active && "text-foreground",
)}
>
{column.header}
<Icon aria-hidden className={cn("size-3.5", !active && "opacity-50")} />
</button>
) : (
column.header
)}
</th>
);
})}
</tr>
</thead>
<tbody>
{rows.map((row, index) => {
const id = rowIds[index];
const isSelected = selected.has(id);
return (
<tr
key={id}
data-state={isSelected ? "selected" : undefined}
className="border-b transition-colors last:border-b-0 hover:bg-muted/40 data-[state=selected]:bg-muted/70"
>
{selectable && (
<td className="w-10 py-3 pl-4">
<Checkbox
aria-label={`Select ${getRowLabel ? getRowLabel(row) : id}`}
checked={isSelected}
onChange={(event) => toggleRow(index, (event.nativeEvent as MouseEvent).shiftKey)}
/>
</td>
)}
{columns.map((column) => (
<td
key={column.id}
className={cn(
"px-4 py-3 align-middle",
column.align === "right" && "text-right tabular-nums",
column.hideBelow && HIDE[column.hideBelow],
column.className,
)}
>
{column.cell ? column.cell(row) : column.accessor ? String(display(column.accessor(row))) : null}
</td>
))}
</tr>
);
})}
{!rows.length && (
<tr>
<td colSpan={colSpan} className="px-4 py-14 text-center">
{data.length === 0 && emptyState ? (
emptyState
) : (
<div className="mx-auto flex max-w-xs flex-col items-center">
<span className="grid size-10 place-items-center rounded-full bg-muted text-muted-foreground">
<SearchX aria-hidden className="size-5" />
</span>
<p className="mt-3 font-medium">No results</p>
{filtersActive && (
<button
type="button"
onClick={() => {
setQuery("");
setFacetValue(null);
}}
className={cn("mt-3 h-8 rounded-md border px-3 text-sm font-medium hover:bg-accent hover:text-accent-foreground", focusRing)}
>
Clear filters
</button>
)}
</div>
)}
</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-3 pt-3 text-sm text-muted-foreground">
<p aria-live="polite" className="tabular-nums">
{selected.size > 0 ? `${selected.size} of ${data.length} selected` : `${sorted.length} ${sorted.length === 1 ? "result" : "results"}`}
</p>
<div className="flex items-center gap-4 sm:gap-6">
<label className="hidden items-center gap-2 sm:flex">
Rows
<select
value={pageSize}
onChange={(event) => setPageSize(Number(event.target.value))}
className={cn("h-8 rounded-md border border-input bg-background px-2 text-sm text-foreground dark:[color-scheme:dark]", focusRing)}
>
{pageSizes.map((size) => (
<option key={size} value={size}>
{size}
</option>
))}
</select>
</label>
<span className="tabular-nums">
{sorted.length ? `${current * pageSize + 1}–${Math.min(sorted.length, (current + 1) * pageSize)} of ${sorted.length}` : "0 of 0"}
</span>
<div className="flex gap-1">
<button
type="button"
onClick={() => setPage(current - 1)}
disabled={current === 0}
aria-label="Previous page"
className={cn("grid size-8 place-items-center rounded-md border bg-background text-foreground hover:bg-accent disabled:pointer-events-none disabled:opacity-40", focusRing)}
>
<ChevronLeft aria-hidden className="size-4" />
</button>
<button
type="button"
onClick={() => setPage(current + 1)}
disabled={current >= pageCount - 1}
aria-label="Next page"
className={cn("grid size-8 place-items-center rounded-md border bg-background text-foreground hover:bg-accent disabled:pointer-events-none disabled:opacity-40", focusRing)}
>
<ChevronRight aria-hidden className="size-4" />
</button>
</div>
</div>
</div>
</div>
);
}
