import { useState } from "react";
import { CalendarDate } from "@internationalized/date";
import { DataTable, useDataTableUrl, type DataTableColumn } from "@senvenli/react/collection";
import { Badge } from "@senvenli/react/display";
const STATUS = {
paid: { label: "Paid", tone: "success" },
pending: { label: "Pending", tone: "warning" },
shipped: { label: "Shipped", tone: "information" },
refunded: { label: "Refunded", tone: "neutral" },
} as const;
type Status = keyof typeof STATUS;
type Order = { id: string; customer: string; date: string; status: Status; total: number };
// Forty fixed orders: index arithmetic, never a random value or today's date.
const CUSTOMERS = ["Ada Lovelace", "Grace Hopper", "Alan Turing", "Katherine Johnson", "Margaret Hamilton", "Barbara Liskov", "Donald Knuth"];
const STATUSES: Status[] = ["paid", "pending", "paid", "shipped", "paid", "refunded"];
const FIRST_DAY = new CalendarDate(2026, 2, 7);
const ORDERS: Order[] = Array.from({ length: 40 }, (_, index) => ({
id: `SO-${1042 + index}`,
customer: CUSTOMERS[index % CUSTOMERS.length]!,
date: FIRST_DAY.add({ days: index }).toString(),
status: STATUSES[index % STATUSES.length]!,
total: 45 + ((index * 37) % 23) * 18.5,
}));
const usd = new Intl.NumberFormat("en", { style: "currency", currency: "USD" });
const day = new Intl.DateTimeFormat("en", { month: "short", day: "numeric", timeZone: "UTC" });
const COLUMNS: DataTableColumn<Order>[] = [
{ key: "id", header: "Order", isRowHeader: true, isSortable: true },
{ key: "customer", header: "Customer", isSortable: true },
// Sorted and searched by the ISO date under `key`, shown short.
{ key: "date", header: "Date", isSortable: true, isHideable: true, render: (order) => day.format(new Date(order.date)) },
{ key: "status", header: "Status", isHideable: true, render: (order) => <Badge tone={STATUS[order.status].tone}>{STATUS[order.status].label}</Badge> },
{ key: "total", header: "Total", align: "end", isSortable: true, render: (order) => usd.format(order.total) },
];
const FILTERS = [{ key: "status", label: "Status", options: Object.entries(STATUS).map(([id, status]) => ({ id, label: status.label })) }];
const SORT = { column: "date", direction: "descending" } as const;
export default function Example() {
const [orders, setOrders] = useState(ORDERS);
// The view lives in the URL (?orders.page=2&orders.status=paid); the prefix keeps two tables on a page apart.
const url = useDataTableUrl({ filters: FILTERS, defaultSort: SORT, urlKey: "orders" });
return (
<DataTable
{...url}
aria-label="Orders"
rows={orders}
columns={COLUMNS}
filters={FILTERS}
defaultSort={SORT}
pageSize={10}
bulkActions={[
{
id: "ship",
label: "Mark as shipped",
// Gets the selected ids from every page; the selection clears once this returns.
onAction: (keys) => setOrders((current) => current.map((order) => (keys.includes(order.id) ? { ...order, status: "shipped" } : order))),
},
]}
/>
);
}import { DataTable } from "@senvenli/react/collection";Examples
A server list
`query` fetches one page for the current view; the table shows loading, empty and error states itself.import { DataTable, useDataTableUrl, type DataTableQuery, type DataTableResult } from "@senvenli/react/collection";
import { EmptyState } from "@senvenli/react/feedback";
type Customer = { id: string; name: string; city: string; orders: number };
const NAMES = ["Ada Lovelace", "Grace Hopper", "Alan Turing", "Katherine Johnson", "Margaret Hamilton", "Barbara Liskov", "Donald Knuth", "Edsger Dijkstra"];
const CITIES = ["Boston", "Chicago", "Denver", "Portland", "Austin"];
const CUSTOMERS: Customer[] = Array.from({ length: 23 }, (_, index) => ({
id: `C-${200 + index}`,
name: NAMES[index % NAMES.length]!,
city: CITIES[index % CITIES.length]!,
orders: 3 + ((index * 11) % 17),
}));
// Stands in for your API: it gets the page, the page size, the search, the sort and the filters.
async function fetchCustomers({ page, pageSize, search }: DataTableQuery): Promise<DataTableResult<Customer>> {
await new Promise((resolve) => setTimeout(resolve, 400));
const found = CUSTOMERS.filter((customer) => customer.name.toLowerCase().includes(search.trim().toLowerCase()));
return { rows: found.slice((page - 1) * pageSize, page * pageSize), total: found.length };
}
export default function Example() {
const url = useDataTableUrl({ urlKey: "customers" });
return (
<DataTable
{...url}
aria-label="Customers"
query={fetchCustomers}
pageSize={5}
columns={[
{ key: "name", header: "Customer" },
{ key: "city", header: "City" },
{ key: "orders", header: "Orders", align: "end" },
]}
emptyState={<EmptyState size="small" icon="inbox" title="No customers yet" description="Customers appear here after their first order." />}
/>
);
}Guidelines
When to use it
- A record list people search, filter and act on in bulk: orders, customers, invoices.
Use something else when
- A short, fixed list with no tools. Table
Accessibility
Keyboard
| Keys | What happens |
|---|---|
| Arrow keys | Move between cells and rows. |
| Tab | Moves between the toolbar, the table and the pager. |
Built in
- Loading, empty, no-results and failed states have their own copy.
- The selected count is announced in the bulk bar.
You provide
- An aria-label, and labels for filters and bulk actions.
API reference
DataTable
| Prop | Type | Default | Description |
|---|---|---|---|
aria-labelRequired | string | – | Names the table ("Orders"). |
columnsRequired | readonly DataTableColumn<T>[] | – | |
rowKey | (row: T) => Key | – | The row's stable id; |
filters | readonly DataTableFilter[] | – | |
bulkActions | readonly DataTableBulkAction[] | – | |
defaultSort | SortDescriptor | – | |
columnVisibility | Readonly<Record<string, boolean>> | – | Column key → shown; columns left out are shown. Pass with |
onColumnVisibilityChange | (visibility: Record<string, boolean>) => void | – | |
onRowAction | (key: Key) => void | – | Opens the record (row press while nothing is selected). |
pageSize | number | – | 20 by default. |
formatRange | (from: number, to: number, total: number) => string | – | The range sentence: (41, 60, 1204) → "41–60 of 1,204". |
emptyState | React.ReactNode | – | What an empty list shows (with no search or filter active): an |
view | DataTableView | – | The view (page, sort, search, filters), controlled. Keep it in the URL with |
defaultView | Partial<DataTableView> | – | The first view when uncontrolled: page 1, the default sort, no search and no filters by default. |
onViewChange | (view: DataTableView) => void | – | Called with the whole next view on every change (a new sort, search, filter or page). |
density | Density | – |
|
query | (view: DataTableQuery, signal: AbortSignal) => Promise<DataTableResult<T>> | – | A server list: fetches one page for the view; aborted when the view changes again. It is read when the view changes, not when the function does: for a list that depends on something else (a parent tab), give the DataTable a |
rows | readonly T[] | – | A client list: searched, filtered and sorted here; paged, or virtualized when long. |
virtualizeAbove | number | – | Client lists longer than this render only the rows in view instead of pages. 200 by default. |
height | number | – | The virtualized list's height in px. 480 by default. |
aria-labelRequiredstringNames the table ("Orders").
columnsRequiredreadonly DataTableColumn<T>[]rowKey(row: T) => KeyThe row's stable id;
row.idby default. Selection is kept by it across pages. Ids must be unique within the list; build one from the fields that are when the data has none (${row.date}:${row.channel}). A repeated id on a page still renders every row: the later ones are keyeda#2,a#3, … in row order, and selection, bulk actions andonRowActionreceive those suffixed keys; a development warning names the repeated ids. A suffixed key follows the row's position, not the row: after a sort, filter or page change a selection made through it can move to another copy, and an id repeated on two pages is one key, so selecting it on one page selects it on both.filtersreadonly DataTableFilter[]bulkActionsreadonly DataTableBulkAction[]defaultSortSortDescriptorcolumnVisibilityReadonly<Record<string, boolean>>Column key → shown; columns left out are shown. Pass with
onColumnVisibilityChangeto own it.onColumnVisibilityChange(visibility: Record<string, boolean>) => voidonRowAction(key: Key) => voidOpens the record (row press while nothing is selected).
pageSizenumber20 by default.
formatRange(from: number, to: number, total: number) => stringThe range sentence: (41, 60, 1204) → "41–60 of 1,204".
emptyStateReact.ReactNodeWhat an empty list shows (with no search or filter active): an
EmptyState size="small"with the action that fills it. "No records yet" by default.viewDataTableViewThe view (page, sort, search, filters), controlled. Keep it in the URL with
useDataTableUrl, or anywhere else; left out, the table keeps it itself.defaultViewPartial<DataTableView>The first view when uncontrolled: page 1, the default sort, no search and no filters by default.
onViewChange(view: DataTableView) => voidCalled with the whole next view on every change (a new sort, search, filter or page).
densityDensitycompact(36px rows) by default: DataTable is the dense working list of a back office.query(view: DataTableQuery, signal: AbortSignal) => Promise<DataTableResult<T>>A server list: fetches one page for the view; aborted when the view changes again. It is read when the view changes, not when the function does: for a list that depends on something else (a parent tab), give the DataTable a
keyfrom it so it starts afresh.rowsreadonly T[]A client list: searched, filtered and sorted here; paged, or virtualized when long.
virtualizeAbovenumberClient lists longer than this render only the rows in view instead of pages. 200 by default.
heightnumberThe virtualized list's height in px. 480 by default.