Data Table
Table primitives for reading figures: a sticky header, scroll-edge fades instead of hard dividers, sortable headers with aria-sort, and digits that line up.
Preview
| / | 48,210 | 31,022 | 38.2% | Up6.1% |
|---|---|---|---|---|
| /pricing | 12,904 | 9,810 | 41.7% | Up12.4% |
| /docs/getting-started | 10,388 | 7,290 | 22.9% | Down3.2% |
| /blog/launch | 8,822 | 8,011 | 64.0% | Up48.5% |
| /changelog | 4,120 | 2,988 | 30.1% | Down0.8% |
| /docs/api | 3,995 | 2,104 | 18.4% | Up4.0% |
| /careers | 1,840 | 1,602 | 55.3% | Down9.6% |
| /about | 1,502 | 1,311 | 49.9% | Up1.2% |
Install
npx shadcn@latest add @dxbh-ui/data-table
Add the @dxbh-ui registry to components.json once:
{
"registries": {
"@dxbh-ui": "https://ui.dxbh.dev/r/{name}.json"
}
}Usage
"use client";
import { DataBody, DataCell, DataHead, DataRow, DataTable, DataTh, useDataSort } from "@/components/ui/data-table/data-table";
import { Delta } from "@/components/ui/delta/delta";
type Row = { page: string; views: number; visitors: number; bounce: number; change: number };
const data: Row[] = [
{ page: "/", views: 48210, visitors: 31022, bounce: 38.2, change: 6.1 },
{ page: "/pricing", views: 12904, visitors: 9810, bounce: 41.7, change: 12.4 },
{ page: "/docs/getting-started", views: 10388, visitors: 7290, bounce: 22.9, change: -3.2 },
{ page: "/blog/launch", views: 8822, visitors: 8011, bounce: 64.0, change: 48.5 },
{ page: "/changelog", views: 4120, visitors: 2988, bounce: 30.1, change: -0.8 },
{ page: "/docs/api", views: 3995, visitors: 2104, bounce: 18.4, change: 4.0 },
{ page: "/careers", views: 1840, visitors: 1602, bounce: 55.3, change: -9.6 },
{ page: "/about", views: 1502, visitors: 1311, bounce: 49.9, change: 1.2 },
];
const n = new Intl.NumberFormat("en-US");
export default function DataTableDemo() {
const { rows, sortProps } = useDataSort(data, { initial: { key: "views", direction: "descending" } });
return (
<div className="w-full max-w-2xl rounded-xl border bg-card pt-4">
<DataTable caption="Top pages, last 30 days" showCaption inset maxHeight={260} minWidth={520} className="[&_caption]:px-5 sm:[&_caption]:px-6">
<DataHead>
<DataTh {...sortProps("page")}>Page</DataTh>
<DataTh numeric {...sortProps("views", "descending")}>Views</DataTh>
<DataTh numeric {...sortProps("visitors", "descending")}>Visitors</DataTh>
<DataTh numeric {...sortProps("bounce", "descending")}>Bounce</DataTh>
<DataTh numeric {...sortProps("change", "descending")}>Change</DataTh>
</DataHead>
<DataBody>
{rows.map((r) => (
<DataRow key={r.page}>
<DataCell rowHeader emphasis className="font-mono text-[13px]">
{r.page}
</DataCell>
<DataCell numeric emphasis>{n.format(r.views)}</DataCell>
<DataCell numeric>{n.format(r.visitors)}</DataCell>
<DataCell numeric>{r.bounce.toFixed(1)}%</DataCell>
<DataCell numeric>
<Delta dir={r.change > 0 ? "up" : r.change < 0 ? "down" : "flat"} value={`${Math.abs(r.change).toFixed(1)}%`} />
</DataCell>
</DataRow>
))}
</DataBody>
</DataTable>
</div>
);
}Props
| Prop | Type | Default |
|---|---|---|
caption*What the table is. Screen-reader only unless showCaption. | ReactNode | — |
showCaptionShow the caption visually. | boolean | false |
minWidthScroll horizontally below this width. | number | string | — |
maxHeightScroll vertically past this height; the header sticks. | number | string | — |
insetPad the first and last columns for an edge-to-edge table. | boolean | false |
DataTh.numeric / DataCell.numericRight-align with tabular digits. | boolean | false |
DataTh.sortedThis column's current sort. | "ascending" | "descending" | null | — |
DataTh.onSortMake the header a sort button. | () => void | — |
useDataSort(rows, { initial, accessor })Client-side sorting; spread sortProps(key) onto a DataTh. | { rows, sort, setSort, sortProps(key, firstDirection?) } | — |
Polish
- Header cells stick when the table scrolls, and rows fade out beneath them with a scroll-edge mask that only appears once scrolled.
- Left and right edges fade only while there is more to scroll that way; scroll state is written straight to the element, not through React.
- Sortable headers are real buttons with aria-sort on the sorted column, a 0.97 press, and a hover/focus hint on unsorted columns.
- Sorting is stable, natural for text, and keeps empty values last in both directions.
- Numeric cells are right-aligned with tabular-nums so columns line up on their digits.
- Adds the missing tbody (DataBody) so the markup is valid and hydrates cleanly.
- Brand rule and ink classes replaced with shadcn border and foreground tokens.
Source
"use client";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode, type ThHTMLAttributes, type TdHTMLAttributes, type HTMLAttributes } from "react";
import { ArrowDown, ArrowUp, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
export type SortDirection = "ascending" | "descending";
export type SortState = { key: string; direction: SortDirection } | null;
const FADE = "24px";
export type DataTableProps = {
/** What the table is. Read by screen readers; shown when `showCaption` is set. */
caption: ReactNode;
showCaption?: boolean;
/** Scroll horizontally below this width instead of crushing columns. */
minWidth?: number | string;
/** Scroll vertically past this height; the header sticks. */
maxHeight?: number | string;
/** Pad the first and last column, for a table that runs edge to edge in a Panel. */
inset?: boolean;
className?: string;
tableClassName?: string;
children: ReactNode;
};
/**
* A table for reading numbers. Headers stick when it scrolls, and instead of
* hard dividers the scroll edges fade: the sides fade only while there is
* more to scroll that way, and rows fade out under the sticky header.
*
* Set `--data-table-surface` (defaults to the card colour) when the table
* sits on another background, so the sticky header and its fade match.
*/
export function DataTable({ caption, showCaption = false, minWidth, maxHeight, inset = false, className, tableClassName, children }: DataTableProps) {
const ref = useRef<HTMLDivElement>(null);
// Per-frame scroll state goes straight onto the element, not through React.
const update = useCallback(() => {
const el = ref.current;
if (!el) return;
const left = Math.abs(el.scrollLeft);
const overflowX = el.scrollWidth - el.clientWidth;
el.style.setProperty("--data-table-fade-l", left > 1 ? FADE : "0px");
el.style.setProperty("--data-table-fade-r", overflowX - left > 1 ? FADE : "0px");
el.toggleAttribute("data-scrolled-y", el.scrollTop > 0);
}, []);
useEffect(() => {
const el = ref.current;
if (!el) return;
update();
if (typeof ResizeObserver === "undefined") return;
const ro = new ResizeObserver(update);
ro.observe(el);
if (el.firstElementChild) ro.observe(el.firstElementChild);
return () => ro.disconnect();
}, [update]);
const mask =
"linear-gradient(to right, transparent, #000 var(--data-table-fade-l, 0px), #000 calc(100% - var(--data-table-fade-r, 0px)), transparent)";
return (
<div
ref={ref}
data-slot="data-table"
onScroll={update}
className={cn(
"group/data-table relative overflow-auto overscroll-x-contain [--data-table-surface:var(--card)]",
inset && "[&_tr>*:first-child]:pl-5 sm:[&_tr>*:first-child]:pl-6 [&_tr>*:last-child]:pr-5 sm:[&_tr>*:last-child]:pr-6",
className,
)}
style={{ maxHeight, maskImage: mask, WebkitMaskImage: mask }}
>
<table className={cn("w-full border-separate border-spacing-0 text-sm", tableClassName)} style={minWidth ? { minWidth } : undefined}>
<caption className={cn(showCaption ? "pb-3 text-left text-sm font-medium text-foreground" : "sr-only")}>{caption}</caption>
{children}
</table>
</div>
);
}
export function DataHead({ className, children, ...props }: HTMLAttributes<HTMLTableSectionElement>) {
return (
<thead data-slot="data-head" className={className} {...props}>
<tr>{children}</tr>
</thead>
);
}
export function DataBody(props: HTMLAttributes<HTMLTableSectionElement>) {
return <tbody data-slot="data-body" {...props} />;
}
export type DataThProps = Omit<ThHTMLAttributes<HTMLTableCellElement>, "children"> & {
/** Right-aligned with tabular digits, for a column of figures. */
numeric?: boolean;
/** This column's current sort, if it is the sorted one. */
sorted?: SortDirection | null;
/** Makes the header a sort button. */
onSort?: () => void;
children: ReactNode;
};
export function DataTh({ numeric = false, sorted = null, onSort, className, children, ...props }: DataThProps) {
const Icon = sorted === "ascending" ? ArrowUp : sorted === "descending" ? ArrowDown : ChevronsUpDown;
return (
<th
scope="col"
aria-sort={onSort && sorted ? sorted : undefined}
data-slot="data-th"
className={cn(
// Sticky cells, not a sticky thead, so the fade below can hang off each one.
"sticky top-0 z-10 border-b bg-(--data-table-surface) pb-2.5 text-xs font-medium whitespace-nowrap text-muted-foreground [&:not(:last-child)]:pr-4",
"after:pointer-events-none after:absolute after:inset-x-0 after:top-full after:h-4 after:bg-linear-to-b after:from-(--data-table-surface) after:to-transparent after:opacity-0 group-data-[scrolled-y]/data-table:after:opacity-100",
numeric ? "text-right tabular-nums" : "text-left",
className,
)}
{...props}
>
{onSort ? (
<button
type="button"
onClick={onSort}
className={cn(
"group/sort -my-1 inline-flex cursor-pointer items-center gap-1 rounded-sm py-1 outline-none select-none",
"transition-transform duration-(--duration-press,120ms) ease-out active:scale-[0.97]",
"hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50",
sorted && "text-foreground",
numeric && "flex-row-reverse",
)}
>
{children}
<Icon
aria-hidden="true"
className={cn(
"size-3.5 shrink-0",
!sorted && "opacity-0 group-hover/sort:opacity-60 group-focus-visible/sort:opacity-60",
)}
/>
</button>
) : (
children
)}
</th>
);
}
export function DataRow({ className, ...props }: HTMLAttributes<HTMLTableRowElement>) {
return <tr data-slot="data-row" className={cn("[&:not(:first-child)>*]:border-t", className)} {...props} />;
}
export type DataCellProps = TdHTMLAttributes<HTMLTableCellElement> & {
/** Right-aligned with tabular digits, so columns line up on their digits. */
numeric?: boolean;
/** The figure the row is about, in full ink. */
emphasis?: boolean;
/** Render as the row's `<th scope="row">`. */
rowHeader?: boolean;
};
export function DataCell({ numeric = false, emphasis = false, rowHeader = false, className, ...props }: DataCellProps) {
const Tag = rowHeader ? "th" : "td";
return (
<Tag
scope={rowHeader ? "row" : undefined}
data-slot="data-cell"
data-numeric={numeric || undefined}
className={cn(
"py-2.5 font-normal whitespace-nowrap [&:not(:last-child)]:pr-4",
numeric ? "text-right tabular-nums" : "text-left",
emphasis ? "font-medium text-foreground" : "text-foreground/80",
className,
)}
{...props}
/>
);
}
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
/** Compare two cell values: numbers numerically, text naturally, empties last. */
export function compareValues(a: unknown, b: unknown): number {
const emptyA = a === null || a === undefined || a === "" || (typeof a === "number" && Number.isNaN(a));
const emptyB = b === null || b === undefined || b === "" || (typeof b === "number" && Number.isNaN(b));
if (emptyA || emptyB) return emptyA === emptyB ? 0 : emptyA ? 1 : -1;
if (typeof a === "number" && typeof b === "number") return a - b;
if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();
return collator.compare(String(a), String(b));
}
/** Sort rows by a key. Stable, and empty values stay last in either direction. */
export function sortRows<T>(rows: readonly T[], sort: SortState, accessor: (row: T, key: string) => unknown): T[] {
if (!sort) return [...rows];
const sign = sort.direction === "ascending" ? 1 : -1;
return [...rows].sort((ra, rb) => {
const a = accessor(ra, sort.key);
const b = accessor(rb, sort.key);
const order = compareValues(a, b);
const emptyFirst = compareValues(a, undefined) === 0 || compareValues(b, undefined) === 0;
return emptyFirst ? order : order * sign;
});
}
const byKey = <T,>(row: T, key: string) => (row as Record<string, unknown>)[key];
/**
* Client-side sorting for a DataTable. Spread `sortProps(key)` onto a DataTh.
* A new column starts at `firstDirection` (pass "descending" for figures,
* where the biggest usually matters); clicking again flips it.
*/
export function useDataSort<T>(
rows: readonly T[],
{ initial = null, accessor = byKey }: { initial?: SortState; accessor?: (row: T, key: string) => unknown } = {},
) {
const [sort, setSort] = useState<SortState>(initial);
const sorted = useMemo(() => sortRows(rows, sort, accessor), [rows, sort, accessor]);
const sortProps = (key: string, firstDirection: SortDirection = "ascending") => ({
sorted: sort?.key === key ? sort.direction : null,
onSort: () =>
setSort((s) =>
s?.key === key
? { key, direction: s.direction === "ascending" ? "descending" : "ascending" }
: { key, direction: firstDirection },
),
});
return { rows: sorted, sort, setSort, sortProps };
}Extracted from Vesrelle/components/data/data-table.tsx at 4619651.