Data display
DataGrid
An interactive grid for data people work in: one tab stop with arrow-key navigation between cells, sorting, search, pagination, selection, cell editing, multi-level grouping with totals, tree data, master–detail rows, spreadsheet-style ranges with copy, paste, fill and undo, CSV and Excel export, resizable and hideable columns, and row and column virtualization for tens of thousands of rows.
import '@reactloom/data-grid/styles.css';
import { DataGrid } from '@reactloom/data-grid';Examples
Sorting and pagination
import { DataGrid, type DataGridColumn } from '@reactloom/data-grid';
import { Badge } from '@reactloom/ui';
import { makeOrders, money, type Order } from './data';
const tone = { Paid: 'success', Pending: 'warning', Refunded: 'neutral' } as const;
const columns: Array<DataGridColumn<Order>> = [
{ key: 'id', header: 'Order', sortable: true, width: 120 },
{ key: 'customer', header: 'Customer', sortable: true, width: 190 },
{ key: 'status', header: 'Status', sortable: true, width: 130, cell: (o) => <Badge tone={tone[o.status]}>{o.status}</Badge> },
{ key: 'items', header: 'Items', sortable: true, align: 'end', width: 90 },
{ key: 'total', header: 'Total', sortable: true, align: 'end', width: 130, cell: (o) => money.format(o.total) },
{ key: 'placed', header: 'Placed', sortable: true, width: 130 },
];
const rows = makeOrders(57);
export default function Example() {
return (
<div style={{ width: '100%' }}>
<DataGrid aria-label="Recent orders" columns={columns} rows={rows} getRowId={(o) => o.id} pageSize={8} defaultSort={{ column: 'placed', direction: 'descending' }} />
</div>
);
}Search, column visibility and selection
The toolbar is ordinary @reactloom/ui components wired to the grid’s props.
0 selected
import { DataGrid, type DataGridColumn } from '@reactloom/data-grid';
import { Button, Checkbox, HStack, PopoverContent, PopoverRoot, PopoverTrigger, SearchInput, Stack, Text } from '@reactloom/ui';
import { useState } from 'react';
import { makeOrders, money, type Order } from './data';
const columns: Array<DataGridColumn<Order>> = [
{ key: 'id', header: 'Order', sortable: true, width: 120, hideable: false },
{ key: 'customer', header: 'Customer', sortable: true, width: 190 },
{ key: 'status', header: 'Status', sortable: true, width: 120 },
{ key: 'region', header: 'Region', sortable: true, width: 110 },
{ key: 'total', header: 'Total', sortable: true, align: 'end', width: 130, cell: (o) => money.format(o.total) },
];
const rows = makeOrders(57);
export default function Example() {
const [search, setSearch] = useState('');
const [selected, setSelected] = useState<string[]>([]);
const [visibility, setVisibility] = useState<Record<string, boolean>>({ region: false });
return (
<Stack gap="3" style={{ width: '100%' }}>
<HStack gap="3" align="center" wrap>
<div style={{ flex: '1 1 14rem', maxWidth: 280 }}>
<SearchInput aria-label="Search orders" placeholder="Search orders…" value={search} onValueChange={setSearch} />
</div>
<PopoverRoot placement="bottom-end">
<PopoverTrigger size="sm">Columns</PopoverTrigger>
<PopoverContent size="sm" aria-label="Visible columns">
<Stack gap="2">
{columns.filter((c) => c.hideable !== false).map((c) => (
<Checkbox
key={c.key}
label={c.header}
checked={visibility[c.key] !== false}
onCheckedChange={(on) => setVisibility((v) => ({ ...v, [c.key]: on }))}
/>
))}
</Stack>
</PopoverContent>
</PopoverRoot>
<Text size="sm" tone="muted">{selected.length} selected</Text>
<Button size="sm" variant="secondary" disabled={selected.length === 0} onClick={() => setSelected([])}>
Clear selection
</Button>
</HStack>
<DataGrid
aria-label="Orders"
columns={columns}
rows={rows}
getRowId={(o) => o.id}
search={search}
pageSize={8}
selectionMode="multiple"
selectedIds={selected}
onSelectionChange={setSelected}
columnVisibility={visibility}
onColumnVisibilityChange={setVisibility}
isRowSelectable={(o) => o.status !== 'Refunded'}
density="compact"
/>
</Stack>
);
}10,000 rows
Only visible rows are rendered; positions are kept with aria-rowindex.
import { DataGrid, type DataGridColumn } from '@reactloom/data-grid';
import { makeOrders, money, type Order } from './data';
const columns: Array<DataGridColumn<Order>> = [
{ key: 'id', header: 'Order', sortable: true, width: 120 },
{ key: 'customer', header: 'Customer', sortable: true, width: 190 },
{ key: 'region', header: 'Region', sortable: true, width: 110 },
{ key: 'items', header: 'Items', sortable: true, align: 'end', width: 90 },
{ key: 'total', header: 'Total', sortable: true, align: 'end', width: 130, cell: (o) => money.format(o.total) },
];
// 10,000 rows: only the visible ones are in the DOM; aria-rowindex keeps positions meaningful.
const rows = makeOrders(10_000);
export default function Example() {
return (
<div style={{ width: '100%' }}>
<DataGrid aria-label="All orders" columns={columns} rows={rows} getRowId={(o) => o.id} height={380} density="compact" />
</div>
);
}Server-side data
Load a page by row offset. Page back to reuse a loaded range, or search to load a different query.
import { DataGrid, type DataGridColumn, type SortDescriptor } from '@reactloom/data-grid';
import { useDataGridDataSource, type DataGridServerRequest } from '@reactloom/data-grid/server';
import { Button, SearchInput, Stack } from '@reactloom/ui';
import { useState } from 'react';
import { makeOrders, money, type Order } from './data';
const columns: Array<DataGridColumn<Order>> = [
{ key: 'id', header: 'Order', sortable: true, width: 120 },
{ key: 'customer', header: 'Customer', sortable: true, width: 190 },
{ key: 'total', header: 'Total', sortable: true, align: 'end', width: 130, cell: (o) => money.format(o.total) },
];
const database = makeOrders(240);
const pageSize = 10;
// This demo uses in-memory rows. In an app, forward the query and signal to fetch().
async function fetchOrders({ offset, limit, sorts, search, signal }: DataGridServerRequest) {
await new Promise<void>((resolve, reject) => {
const abort = () => { clearTimeout(timer); reject(signal.reason); };
const timer = setTimeout(() => {
signal.removeEventListener('abort', abort);
resolve();
}, 350);
signal.addEventListener('abort', abort, { once: true });
});
const rows = database.filter((order) => order.customer.toLowerCase().includes(search.trim().toLowerCase()));
rows.sort((a, b) => {
for (const { column, direction } of sorts) {
const comparison = column === 'total' ? a.total - b.total
: column === 'customer' ? a.customer.localeCompare(b.customer) : a.id.localeCompare(b.id);
if (comparison) return direction === 'descending' ? -comparison : comparison;
}
return 0;
});
return { rows: rows.slice(offset, offset + limit), rowCount: rows.length };
}
export default function Example() {
const [page, setPage] = useState(1);
const [sorts, setSorts] = useState<SortDescriptor[]>([]);
const [search, setSearch] = useState('');
const { rows, rowCount, loading, error, refresh } = useDataGridDataSource(fetchOrders, { page, pageSize, sorts, search });
return (
<Stack gap="3" style={{ width: '100%' }}>
<SearchInput label="Search server orders" value={search} onValueChange={(value) => { setSearch(value); setPage(1); }} />
{error && <div role="alert">Could not load orders. <Button size="sm" onClick={refresh}>Retry</Button></div>}
<DataGrid
aria-label="Orders (server)"
columns={columns}
rows={rows}
getRowId={(order) => order.id}
manualSorting
manualFiltering
manualPagination
rowCount={rowCount}
pageSize={pageSize}
page={page}
onPageChange={setPage}
sorts={sorts}
onSortsChange={(next) => { setSorts(next); setPage(1); }}
search={search}
loading={loading}
emptyState={error ? 'Orders unavailable' : 'No orders found'}
/>
</Stack>
);
}Column filters and sort priorities
Filter by status or minimum total. Shift-click a header to add or change a secondary sort. Switch to the simulated server to run the same query against paged data.
import { useEffect, useMemo, useState } from 'react';
import { DataGrid, type DataGridColumn, type DataGridFilter, type SortDescriptor } from '@reactloom/data-grid';
import { Button, Checkbox, HStack, Input, Select, Stack } from '@reactloom/ui';
import { makeOrders, money, type Order } from './data';
const columns: DataGridColumn<Order>[] = [
{ key: 'id', header: 'Order', sortable: true, width: 120 },
{ key: 'status', header: 'Status', sortable: true, width: 130 },
{ key: 'total', header: 'Total', sortable: true, align: 'end', width: 130, cell: (order) => money.format(order.total) },
];
const statuses = [
{ value: 'all', label: 'Any status' },
{ value: 'Paid', label: 'Paid' },
{ value: 'Pending', label: 'Pending' },
{ value: 'Refunded', label: 'Refunded' },
];
const initialSorts: SortDescriptor[] = [
{ column: 'status', direction: 'ascending' },
{ column: 'total', direction: 'descending' },
];
const database = makeOrders(120);
const pageSize = 8;
type Query = { page: number; filters: readonly DataGridFilter[]; sorts: readonly SortDescriptor[] };
// This demo handles the two filters offered by its toolbar. In an app, validate the allowed
// columns and operators at your API, then apply the query before slicing the requested page.
function queryDatabase(query: Query) {
const rows = database.filter((row) => query.filters.every((filter) => {
if (filter.column === 'status' && filter.type === 'text') return row.status === filter.value;
if (filter.column === 'total' && filter.type === 'number') return row.total >= filter.value;
return true;
}));
rows.sort((a, b) => {
for (const { column, direction } of query.sorts) {
const difference = column === 'total' ? a.total - b.total
: column === 'status' ? a.status.localeCompare(b.status)
: a.id.localeCompare(b.id);
if (difference) return direction === 'ascending' ? difference : -difference;
}
return 0;
});
const start = (query.page - 1) * pageSize;
return { query, rows: rows.slice(start, start + pageSize), total: rows.length };
}
export default function Example() {
const [status, setStatus] = useState('all');
const [minimum, setMinimum] = useState('');
const [sorts, setSorts] = useState(initialSorts);
const [page, setPage] = useState(1);
const [remote, setRemote] = useState(false);
const [result, setResult] = useState<ReturnType<typeof queryDatabase>>();
const filters = useMemo(() => {
const rules: DataGridFilter[] = [];
if (status !== 'all') rules.push({ column: 'status', type: 'text', operator: 'equals', value: status });
if (minimum && Number.isFinite(Number(minimum))) rules.push({ column: 'total', type: 'number', operator: 'gte', value: Number(minimum) });
return rules;
}, [status, minimum]);
const query = useMemo(() => ({ page, filters, sorts }), [page, filters, sorts]);
useEffect(() => {
if (!remote) return;
const timer = setTimeout(() => setResult(queryDatabase(query)), 250);
return () => clearTimeout(timer);
}, [query, remote]);
const serverPage = result?.query === query ? result : undefined;
function changeSorts(next: SortDescriptor[]) {
setSorts(next);
setPage(1);
}
return (
<Stack gap="3" style={{ width: '100%' }}>
<HStack gap="3" align="end" wrap>
<Select label="Order status" options={statuses} value={status}
onValueChange={(value) => { setStatus(value ?? 'all'); setPage(1); }} />
<Input label="Minimum total" type="number" min={0} step="0.01" value={minimum}
onChange={(event) => { setMinimum(event.target.value); setPage(1); }} />
<Button variant="secondary" onClick={() => { setStatus('all'); setMinimum(''); setPage(1); }}>
Clear filters
</Button>
<Button variant="secondary" onClick={() => changeSorts(initialSorts)}>
Sort by status, then highest total
</Button>
</HStack>
<Checkbox label="Use simulated server" checked={remote} onCheckedChange={(checked) => { setRemote(checked); setPage(1); }} />
<DataGrid aria-label="Order query" columns={columns}
rows={remote ? serverPage?.rows ?? [] : database}
getRowId={(row) => row.id}
sorts={sorts} onSortsChange={changeSorts} filters={filters}
manualSorting={remote} manualFiltering={remote} manualPagination={remote}
rowCount={remote ? serverPage?.total ?? 0 : undefined}
loading={remote && !serverPage}
pageSize={pageSize} page={page} onPageChange={setPage}
/>
</Stack>
);
}Editing cells
Focus a Customer, Status or Items cell and press Enter, F2 or start typing. Enter saves, Escape cancels. Refunded orders are read-only.
import { DataGrid, type DataGridColumn } from '@reactloom/data-grid';
import { Badge } from '@reactloom/ui';
import { useState } from 'react';
import { makeOrders, money, type Order } from './data';
const tone = { Paid: 'success', Pending: 'warning', Refunded: 'neutral' } as const;
const columns: Array<DataGridColumn<Order>> = [
{ key: 'id', header: 'Order', width: 120 },
{
key: 'customer',
header: 'Customer',
width: 200,
editable: true,
validate: (value) => (String(value).trim() ? undefined : 'Enter a customer name'),
},
{
key: 'status',
header: 'Status',
width: 140,
// Refunded orders are final.
editable: (order) => order.status !== 'Refunded',
editor: 'select',
options: [
{ value: 'Paid', label: 'Paid' },
{ value: 'Pending', label: 'Pending' },
{ value: 'Refunded', label: 'Refunded' },
],
cell: (o) => <Badge tone={tone[o.status]}>{o.status}</Badge>,
},
{
key: 'items',
header: 'Items',
align: 'end',
width: 100,
editable: true,
editor: 'number',
validate: (value) => (typeof value === 'number' && Number.isInteger(value) && value > 0 ? undefined : 'Enter a whole number above 0'),
},
{ key: 'total', header: 'Total', align: 'end', width: 130, cell: (o) => money.format(o.total) },
];
export default function Example() {
const [orders, setOrders] = useState(() => makeOrders(6));
return (
<DataGrid
aria-label="Editable orders"
columns={columns}
rows={orders}
getRowId={(o) => o.id}
onCellEdit={({ rowId, column, value }) =>
// Save to your API here; return the promise to show "Saving…" and surface errors.
setOrders((rows) => rows.map((o) => (o.id === rowId ? { ...o, [column]: value } : o)))
}
/>
);
}Grouping with totals
Group rows open and close with Enter or Space; pagination counts group rows too.
import { DataGrid, type DataGridColumn } from '@reactloom/data-grid';
import { Select, Stack } from '@reactloom/ui';
import { useState } from 'react';
import { makeOrders, money, type Order } from './data';
const columns: Array<DataGridColumn<Order>> = [
{ key: 'id', header: 'Order', sortable: true, width: 120 },
{ key: 'customer', header: 'Customer', sortable: true, width: 190 },
{ key: 'status', header: 'Status', sortable: true, width: 120 },
{ key: 'region', header: 'Region', sortable: true, width: 110 },
{ key: 'items', header: 'Items', align: 'end', width: 90, aggregate: 'sum' },
{ key: 'total', header: 'Total', sortable: true, align: 'end', width: 130, cell: (o) => money.format(o.total), aggregate: 'sum', formatAggregate: (n) => money.format(n) },
];
const rows = makeOrders(24);
export default function Example() {
const [groupBy, setGroupBy] = useState<string | null>('region');
return (
<Stack gap="3" style={{ width: '100%' }}>
<div style={{ maxWidth: 220 }}>
<Select
label="Group by"
value={groupBy ?? 'none'}
onValueChange={(v) => setGroupBy(v === 'none' ? null : v)}
options={[
{ value: 'none', label: 'No grouping' },
{ value: 'region', label: 'Region' },
{ value: 'status', label: 'Status' },
{ value: 'customer', label: 'Customer' },
]}
/>
</div>
<DataGrid aria-label="Orders by group" columns={columns} rows={rows} getRowId={(o) => o.id} groupBy={groupBy} pageSize={12} density="compact" />
</Stack>
);
}Export to CSV and Excel
Exports what the user sees — search, sort and visible columns, every page — with values rather than formatted text.
import { DataGrid, type DataGridApi, type DataGridColumn } from '@reactloom/data-grid';
import { Button, SearchInput, Stack } from '@reactloom/ui';
import { useRef, useState } from 'react';
import { makeOrders, money, type Order } from './data';
const columns: Array<DataGridColumn<Order>> = [
{ key: 'id', header: 'Order', sortable: true, width: 120 },
{ key: 'customer', header: 'Customer', sortable: true, width: 200 },
{ key: 'status', header: 'Status', sortable: true, width: 120 },
// The cell shows "$1,204.50"; the CSV gets the number 1204.5.
{ key: 'total', header: 'Total', sortable: true, align: 'end', width: 130, cell: (o) => money.format(o.total) },
];
const rows = makeOrders(40);
export default function Example() {
const api = useRef<DataGridApi<Order>>(null);
const [search, setSearch] = useState('');
const [error, setError] = useState('');
async function exportWorkbook() {
const grid = api.current;
if (!grid) return;
setError('');
try {
const { downloadXlsx } = await import('@reactloom/data-grid/xlsx');
downloadXlsx(grid.getExportColumns(), grid.getRows(), 'orders.xlsx', { sheetName: 'Orders' });
} catch {
setError('The workbook could not be downloaded.');
}
}
return (
<Stack gap="3" style={{ width: '100%' }}>
<Stack direction="row" gap="2" align="end" wrap>
<div style={{ flex: '1 1 14rem', maxWidth: 280 }}>
<SearchInput aria-label="Search orders" placeholder="Search orders…" value={search} onValueChange={setSearch} />
</div>
<Button variant="secondary" onClick={() => api.current?.downloadCsv('orders.csv')}>
Export CSV
</Button>
<Button variant="secondary" onClick={exportWorkbook}>Export Excel</Button>
</Stack>
{error && <p role="alert">{error}</p>}
<DataGrid apiRef={api} aria-label="Exportable orders" columns={columns} rows={rows} getRowId={(o) => o.id} search={search} pageSize={8} />
</Stack>
);
}Pinned columns and saved layouts
Pin a column, change the search or sort, and save the view. Restore it after changing the grid or reloading this page.
import { useRef, useState } from 'react';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridColumnLayout, type DataGridView } from '@reactloom/data-grid';
import { Button, SearchInput, Stack } from '@reactloom/ui';
import { makeOrders, money, type Order } from './data';
const columns: DataGridColumn<Order>[] = [
{ key: 'id', header: 'Order', width: 110, sortable: true },
{ key: 'customer', header: 'Customer', width: 190, sortable: true },
{ key: 'region', header: 'Region', width: 115, sortable: true },
{ key: 'placed', header: 'Placed', width: 145, sortable: true },
{ key: 'total', header: 'Total', width: 125, sortable: true, cell: (order) => money.format(order.total) },
];
const rows = makeOrders(10);
const storageKey = 'plinth.docs.orders-grid-view';
export default function Example() {
const [layout, setLayout] = useState<DataGridColumnLayout>({ pinnedStart: ['id'], pinnedEnd: ['total'] });
const [search, setSearch] = useState('');
const [message, setMessage] = useState('');
const apiRef = useRef<DataGridApi<Order>>(null);
function saveView() {
if (!apiRef.current) return;
try {
localStorage.setItem(storageKey, JSON.stringify(apiRef.current.getView()));
setMessage('View saved to this browser.');
} catch {
setMessage('This browser could not save the view.');
}
}
function restoreView() {
if (!apiRef.current) return;
try {
const saved = localStorage.getItem(storageKey);
if (!saved) {
setMessage('Save a view before restoring it.');
return;
}
const view: DataGridView = JSON.parse(saved);
setMessage(apiRef.current.restoreView(view) ? 'Saved view restored.' : 'This saved view uses an unsupported version.');
} catch {
setMessage('This browser could not restore the view.');
}
}
return (
<Stack gap="3" style={{ inlineSize: '100%', maxInlineSize: 480 }}>
<SearchInput label="Search saved-view orders" value={search} onValueChange={setSearch} />
<Stack direction="row" gap="2" wrap>
<Button size="sm" variant="secondary" onClick={() => setLayout({ ...layout, pinnedEnd: layout.pinnedEnd?.length ? [] : ['total'] })}>
{layout.pinnedEnd?.length ? 'Unpin total' : 'Pin total'}
</Button>
<Button size="sm" variant="secondary" onClick={saveView}>Save view</Button>
<Button size="sm" variant="secondary" onClick={restoreView}>Restore view</Button>
</Stack>
<div role="status">{message}</div>
<DataGrid aria-label="Orders with pinned columns" columns={columns} rows={rows} height={240} getRowId={(row) => row.id}
apiRef={apiRef} columnLayout={layout} onColumnLayoutChange={setLayout}
search={search} onSearchChange={setSearch} reorderableColumns multiSort />
</Stack>
);
}Grouping by several columns
defaultGrouping={['region', 'status']}: each level shows its column name and its own totals.
import { DataGrid, type DataGridColumn } from '@reactloom/data-grid';
import { makeOrders, money, type Order } from './data';
const columns: Array<DataGridColumn<Order>> = [
{ key: 'id', header: 'Order', width: 120 },
{ key: 'customer', header: 'Customer', width: 190 },
{ key: 'region', header: 'Region', width: 110 },
{ key: 'status', header: 'Status', width: 120 },
{ key: 'items', header: 'Items', align: 'end', width: 90, aggregate: 'sum' },
{ key: 'total', header: 'Total', align: 'end', width: 130, cell: (o) => money.format(o.total), aggregate: 'sum', formatAggregate: (n) => money.format(n) },
];
// Region, then status inside each region; every level has its own totals.
export default function Example() {
return <DataGrid aria-label="Orders by region and status" columns={columns} rows={makeOrders(30)} getRowId={(o) => o.id} defaultGrouping={['region', 'status']} density="compact" height={420} />;
}Tree data
getSubRows makes a treegrid. On the Name cell, → expands and ← collapses or moves to the parent. Search keeps the folders around matches.
import { DataGrid, type DataGridColumn } from '@reactloom/data-grid';
import { SearchInput, Stack } from '@reactloom/ui';
import { useState } from 'react';
interface Folder {
id: string;
name: string;
owner: string;
size: number;
children?: Folder[];
}
const tree: Folder[] = [
{ id: 'design', name: 'Design', owner: 'Ada', size: 4200, children: [
{ id: 'brand', name: 'Brand', owner: 'Ada', size: 1800, children: [
{ id: 'logo', name: 'Logo.svg', owner: 'Ada', size: 24 },
{ id: 'palette', name: 'Palette.pdf', owner: 'Grace', size: 310 },
] },
{ id: 'ui', name: 'UI kit', owner: 'Alan', size: 2400 },
] },
{ id: 'finance', name: 'Finance', owner: 'Grace', size: 980, children: [
{ id: 'budget', name: 'Budget 2031.xlsx', owner: 'Grace', size: 88 },
{ id: 'invoices', name: 'Invoices', owner: 'Linus', size: 890, children: [{ id: 'inv-1', name: 'INV-2041.pdf', owner: 'Linus', size: 120 }] },
] },
{ id: 'readme', name: 'Read me.md', owner: 'Alan', size: 4 },
];
const kb = new Intl.NumberFormat('en-US', { style: 'unit', unit: 'kilobyte' });
const columns: Array<DataGridColumn<Folder>> = [
{ key: 'name', header: 'Name', sortable: true, width: 280 },
{ key: 'owner', header: 'Owner', sortable: true, width: 140 },
{ key: 'size', header: 'Size', sortable: true, align: 'end', width: 120, cell: (f) => kb.format(f.size) },
];
// → expands and ← collapses on the Name cell; searching keeps the folders around matches.
export default function Example() {
const [search, setSearch] = useState('');
return (
<Stack gap="3" style={{ width: '100%' }}>
<div style={{ maxWidth: 260 }}>
<SearchInput aria-label="Search files" placeholder="Search files…" value={search} onValueChange={setSearch} />
</div>
<DataGrid aria-label="Files" columns={columns} rows={tree} getRowId={(f) => f.id} getSubRows={(f) => f.children} defaultExpandedRowIds={['design']} search={search} density="compact" />
</Stack>
);
}Master–detail rows
renderDetail adds a toggle column; the detail row spans the grid and its links are reached with Enter.
- Placed
- 2026-02-02
- Items
- 5
- Region
- AMER
- Invoice
- Download ORD-1002.pdf
import { DataGrid, type DataGridColumn } from '@reactloom/data-grid';
import { DescriptionItem, DescriptionList, Link } from '@reactloom/ui';
import { makeOrders, money, type Order } from './data';
const columns: Array<DataGridColumn<Order>> = [
{ key: 'id', header: 'Order', width: 120 },
{ key: 'customer', header: 'Customer', width: 190 },
{ key: 'status', header: 'Status', width: 120 },
{ key: 'total', header: 'Total', align: 'end', width: 130, cell: (o) => money.format(o.total) },
];
const Detail = ({ order }: { order: Order }) => (
<DescriptionList>
<DescriptionItem term="Placed">{order.placed}</DescriptionItem>
<DescriptionItem term="Items">{order.items}</DescriptionItem>
<DescriptionItem term="Region">{order.region}</DescriptionItem>
<DescriptionItem term="Invoice">
<Link href={`#${order.id}`}>Download {order.id}.pdf</Link>
</DescriptionItem>
</DescriptionList>
);
// The detail row spans the grid; Enter moves into its links and Escape returns to the row.
export default function Example() {
return <DataGrid aria-label="Orders with details" columns={columns} rows={makeOrders(8)} getRowId={(o) => o.id} renderDetail={(o) => <Detail order={o} />} defaultDetailRowIds={['ORD-1002']} />;
}Ranges, clipboard, fill and undo
Shift + arrows, Shift + click or drag select cells. Copy and paste work with spreadsheets; one value pasted into a range fills it. Ctrl/⌘ + D fills down, Delete clears, Ctrl/⌘ + Z undoes.
import { DataGrid, type DataGridApi, type DataGridColumn } from '@reactloom/data-grid';
import { Button, HStack, Stack } from '@reactloom/ui';
import { useRef, useState } from 'react';
import { makeOrders, type Order } from './data';
const columns: Array<DataGridColumn<Order>> = [
{ key: 'id', header: 'Order', width: 120 },
{ key: 'customer', header: 'Customer', width: 180, editable: true },
{ key: 'region', header: 'Region', width: 110, editable: true },
{ key: 'items', header: 'Items', align: 'end', width: 90, editable: true, editor: 'number', validate: (v) => (typeof v === 'number' && v < 0 ? 'Use 0 or more' : undefined) },
{ key: 'total', header: 'Total', align: 'end', width: 120, editable: true, editor: 'number' },
];
// Shift + arrows or drag to select; ⌘/Ctrl + C, V, D (fill down), Delete, ⌘/Ctrl + Z.
export default function Example() {
const [rows, setRows] = useState(() => makeOrders(10));
const api = useRef<DataGridApi<Order>>(null);
return (
<Stack gap="3" style={{ width: '100%' }}>
<HStack gap="2">
<Button size="sm" variant="secondary" onClick={() => api.current?.undo()}>
Undo
</Button>
<Button size="sm" variant="secondary" onClick={() => api.current?.redo()}>
Redo
</Button>
</HStack>
<DataGrid
aria-label="Order sheet"
columns={columns}
rows={rows}
getRowId={(o) => o.id}
apiRef={api}
cellSelection
density="compact"
// One call per paste, fill, clear or undo.
onCellsEdit={(edits) =>
setRows((list) => list.map((row) => edits.filter((e) => e.rowId === row.id).reduce((acc, e) => ({ ...acc, [e.column]: e.value }), row)))
}
/>
</Stack>
);
}80 columns
Columns are virtualized too when there are more than 30: only the cells in view are in the page.
import { DataGrid, type DataGridColumn } from '@reactloom/data-grid';
interface Metrics {
id: string;
name: string;
[week: string]: string | number;
}
const weeks = Array.from({ length: 80 }, (_, i) => `w${i + 1}`);
const rows: Metrics[] = Array.from({ length: 200 }, (_, r) => ({
id: `m${r}`,
name: `Metric ${r + 1}`,
...Object.fromEntries(weeks.map((w, c) => [w, ((r + 3) * (c + 7) * 37) % 1000])),
}));
const columns: Array<DataGridColumn<Metrics>> = [{ key: 'name', header: 'Metric', width: 140 }, ...weeks.map((w, i) => ({ key: w, header: `Week ${i + 1}`, align: 'end' as const, width: 96 }))];
// 81 columns × 200 rows: only the cells in view render (rows and columns are virtualized).
export default function Example() {
return <DataGrid aria-label="Weekly metrics" columns={columns} rows={rows} getRowId={(r) => r.id} height={360} density="compact" defaultColumnLayout={{ pinnedStart: ['name'] }} />;
}API reference
DataGrid props
| Prop | Type | Default |
|---|---|---|
columnsrequired | DataGridColumn<Row>[] | — |
rowsrequired | Row[] | — |
getRowIdrequired | (row) => string | — |
aria-label · aria-labelledbyThe grid needs a name. | string | — |
sort / defaultSort / onSortChangeThird click clears. | { column, direction } | null | — |
searchMatches searchable columns; resets to page 1. | string | — |
pageSize · page / defaultPage / onPageChangePages are 1-based. | number | — |
manualSorting · manualFiltering · manualPagination · rowCountServer-side data. | | — |
selectionMode | 'none' | 'multiple' | 'none' |
selectedIds / defaultSelectedIds / onSelectionChange | string[] | — |
isRowSelectable | (row) => boolean | — |
columnVisibility / onColumnVisibilityChangefalse hides a column. | Record<string, boolean> | — |
columnWidths / onColumnWidthsChangePersist resized widths. | Record<string, number> | — |
heightScroll inside with a sticky header. | number | string | — |
virtualizeNeeds height. | boolean | > 100 rows |
density | 'comfortable' | 'compact' | 'comfortable' |
striped · loading · emptyState | | — |
labelsTranslate built-in text. | Partial<DataGridLabels> | — |
onCellEditUpdate your rows. Return a promise to show “Saving…”; a rejection’s message is shown in the cell. | ({ row, rowId, column, value, previousValue }) => void | Promise<void> | — |
groupBy / defaultGroupBy / onGroupByChangeColumn key to group by (client-side). | string | null | — |
defaultGroupsCollapsed | boolean | false |
grouping / defaultGrouping / onGroupingChangeSeveral grouping columns, outermost first. | string[] | — |
getSubRowsTree data (treegrid). | (row) => Row[] | undefined | — |
expandedRowIds / defaultExpandedRowIds / onExpandedRowIdsChangeOpen parents (tree data). | string[] | 'all' | — |
renderDetailMaster–detail rows with a toggle column. | (row) => ReactNode | — |
detailRowIds / defaultDetailRowIds / onDetailRowIdsChange · detailHeightOpen detail rows; estimated height for virtualization. | | — |
cellSelectionCell ranges: select, copy, paste, fill down, clear. | boolean | false |
onCellsEditBatch of edits (paste, fill, clear, undo). Without it, onCellEdit runs once per cell. | (edits) => void | Promise<void> | — |
undoLimitBatches kept for Ctrl/⌘ + Z. | number | 50 |
virtualizeColumnsRender only columns in view. | boolean | > 30 columns |
apiRefgetRows(scope), toCsv(options), downloadCsv(filename, options), undo(), redo(), canUndo(), canRedo(), expandAll(), collapseAll(). | Ref<DataGridApi> | — |
Column filters and multi-column sorting
| Prop | Type | Default |
|---|---|---|
multiSortEnable multi-column sorting. Providing any plural sort prop also enables it. | boolean | false |
sorts · defaultSortsControlled or initial order, highest priority first. In multi-sort mode, use these in place of the single-sort props. | readonly SortDescriptor[] | — |
onSortsChangeReceives the updated sequence after header activation. | (sorts: SortDescriptor[]) => void | — |
filters · defaultFiltersControlled or initial column filters. | readonly DataGridFilter[] | — |
onFiltersChangeReceives filter changes requested through apiRef.current.setFilters(filters). | (filters: readonly DataGridFilter[]) => void | — |
Activate a header to cycle ascending, descending, and off. Hold Shift to keep the other priorities. Header badges show the sort order, and assistive technology receives a description of each ranked column. On touch, offer a toolbar preset or build sort controls using the controlled sorts prop.
Filters read the column’s raw value. Text supports contains, starts with, ends with, and equals using locale-aware case folding. Number and date rules support equality and comparisons. Date rules use epoch milliseconds and match Date cells. Boolean rules match true or false exactly. Empty rules match null, undefined, and empty strings.
All rules must match, including multiple rules on the same column. Column filters run alongside global search before sorting and pagination. Use apiRef.current.getFilters() to read the rules and setFilters([]) to clear an uncontrolled grid. Search and filter changes reset pagination to page one.
With manualFiltering and manualSorting, send the same filter descriptors and sort sequence to your API. Combine these props with manualPagination and the filtered server rowCount for server-owned pages. Validate columns, operators, and values on the server.
Server data source
Import useDataGridDataSource from @reactloom/data-grid/server. Pass a stable loader and the current one-based page, page size, search, filters, and sort priorities. The loader receives the zero-based row offset, limit, query, and an AbortSignal. Return the requested rows and the total match count as rowCount.
Use the returned rows, count, and loading state with the grid’s manual modes. Reset the page to one when changing the query. The hook caches up to 12 completed ranges per instance by default. Set cacheSize to zero to disable caching, or call refresh() after a data mutation or load failure. Render an error and retry control with the returned error and refresh values.
Column layout
| Prop | Type | Default |
|---|---|---|
columnLayout · defaultColumnLayoutColumn keys in order, plus pinnedStart and pinnedEnd groups. Pinning follows the reading direction. | DataGridColumnLayout | — |
onColumnLayoutChangeReceives the layout after keyboard reordering. | (layout: DataGridColumnLayout) => void | — |
reorderableColumnsEnable keyboard reordering within the same pin area. | boolean | false |
Keep layout state in your application to save a view. Use apiRef.current.getColumnLayout() and setColumnLayout(layout) to capture and restore from an uncontrolled grid. Missing column keys are ignored and new columns follow declaration order. Leave enough width between pinned groups for users to read the scrolling columns.
Saved views
Use apiRef.current.getView() to capture a JSON-serializable DataGridView with column order, pinning, visibility, widths, search, filters, sort priorities, and grouping. Store the snapshot in your app and pass it to restoreView(view). The grid preserves row selection and applies the existing page reset when search or filters change.
Controlled settings request updates through their change callbacks. Pair controlled search with onSearchChange, or start with an uncontrolled defaultSearch. A single-sort grid applies the first valid sort from the view. Validate snapshots from external storage before restoring them. restoreView returns false for an unsupported version.
DataGridColumn
| Prop | Type | Default |
|---|---|---|
keyrequiredId and default property. | string | — |
headerrequired | ReactNode | — |
cell | (row) => ReactNode | — |
valueFor sorting and search. | (row) => string | number | Date | boolean | null | — |
sortable | boolean | false |
searchable | boolean | true |
width · minWidth · maxWidthpx | number | 160 · 60 · – |
resizable · hideable | boolean | true |
align | 'start' | 'center' | 'end' | 'start' |
rowHeaderDefault: first column. | boolean | — |
textValueAnnounced name when header is not text. | string | — |
editableCells can be edited. | boolean | (row) => boolean | — |
editorNumbers are parsed in the user’s locale. | 'text' | 'number' | 'select' | (props) => ReactNode | 'text' |
optionsFor the select editor. | { value, label }[] | — |
parse · validateReturn a message to reject an edit. | (text, row) => value · (value, row) => string | undefined | — |
aggregateShown in group rows. | 'sum' | 'avg' | 'min' | 'max' | 'count' | (rows) => ReactNode | — |
formatAggregate | (value: number) => string | — |
exportValueCSV value. Default: value (dates as ISO 8601). | (row) => string | number | Date | … | — |
Export
apiRef.current.downloadCsv('orders.csv') saves the rows the user is looking at — after filtering and sorting, across every loaded page, with the visible columns in order — and announces how many rows were exported. Pass { scope: 'selected' } for selected rows or 'all' for everything. toCsv(columns, rows) is exported for server code and custom flows.
Import toXlsx or downloadXlsx from @reactloom/data-grid/xlsx. Pass the grid’s getExportColumns() and getRows(scope) to export a single worksheet in display order. Numbers and booleans stay typed, dates use ISO text, and formula-looking text stays literal.
- Fields are quoted as RFC 4180 requires; lines end with CRLF; a UTF-8 byte-order mark (
bom) lets Excel read accented text. - Text that a spreadsheet would run as a formula (starting with
=,+,-,@) is prefixed with an apostrophe, following OWASP guidance on CSV injection. Numbers stay numbers. - Cells export their value, not their rendered text:
$1,204.50becomes1204.5; dates become2026-10-02. UseexportValueto change that.
Customization
Extracted from the component’s source on every build, so it matches the code. How the layers fit together is explained in Customization.
State attributes
Target these in your CSS to style states without depending on class names.
| Attribute | Values |
|---|---|
[data-active] | present when on |
[data-align] | present when on |
[data-cell-selection] | present when on |
[data-density] | compact · comfortable |
[data-depth] | present when on |
[data-editable] | present when on |
[data-editing] | present when on |
[data-expanded] | present when on |
[data-in-range] | present when on |
[data-leaf] | present when on |
[data-odd] | present when on |
[data-pinned] | present when on |
[data-resizing] | present when on |
[data-selected] | present when on |
[data-striped] | present when on |
Theme tokens it reads
--pl-color-accent-solid --pl-color-accent-subtle --pl-color-bg-muted --pl-color-bg-subtle --pl-color-bg-surface --pl-color-border-default --pl-color-border-input --pl-color-fg-default --pl-color-fg-muted --pl-focus-ring-color --pl-focus-ring-width --pl-font-size-sm --pl-font-size-xs --pl-radius-lg --pl-radius-sm --pl-radius-xs
Accessibility
- role="grid" with a single tab stop; arrow keys move between cells, mirrored in right-to-left layouts.
- A cell with one widget (sort button, checkbox) focuses it directly; a cell with several is entered with Enter or F2 and left with Escape.
- aria-rowcount / aria-rowindex / aria-colindex keep positions correct with pagination and virtualization; selected rows expose aria-selected.
- Sort changes are announced; column widths can be changed with Alt + ←/→ as well as by dragging.
- Editing follows the APG grid pattern: Enter or F2 (or typing) opens an editor named after the column and row (“Edit Customer, ORD-1002”); Enter saves and Escape cancels, both returning focus to the cell. Arrow keys stay inside the editor. Rejected values set aria-invalid and the message is the editor’s description and is announced; successful saves are announced too. Cells that cannot be edited in an otherwise editable column are aria-readonly.
- Group rows are rows with one cell spanning the grid (aria-colspan) and a button with aria-expanded. Moving through a group row keeps your column.
- For read-only data without cell navigation, prefer Table from @reactloom/ui — it is simpler for screen-reader users.
| Key | Action |
|---|---|
| ← → ↑ ↓ | Move between cells |
| Home / End | First / last cell in the row |
| Ctrl + Home / End | First / last cell in the grid |
| Page Up / Page Down | Move by a screenful |
| Enter / F2 | Edit an editable cell, or interact with the widgets in a cell |
| Typing / Backspace | Start editing with that character / empty |
| Enter (editing) | Save |
| Escape | Cancel editing; back to the cell |
| Enter / Space (group row) | Expand or collapse the group |
| Enter / Space (header) | Sort |
| Shift + Enter / Space (header) | Add, cycle, or remove a sort priority while keeping the others |
| Alt + ← / → | Narrower / wider column |
| Alt + Shift + ← / → | Move column within its pin area when enabled |
| → / ← (tree, Name cell) | Expand / collapse, or move to the parent row |
| Shift + arrows · Shift + Home / End | Extend the cell range (cellSelection) |
| Ctrl/⌘ + A | Select every cell (cellSelection) |
| Ctrl/⌘ + C / V | Copy the range or cell / paste from a spreadsheet |
| Ctrl/⌘ + D | Fill the range down from its first row |
| Delete (range) | Clear the editable cells in the range |
| Ctrl/⌘ + Z · Ctrl/⌘ + Shift + Z or Ctrl + Y | Undo / redo the last change made in the grid |
Usage guidelines
Do
- Use for large or editable data people work in.
- Right-align numbers and sort them by value.
- Validate edits in the column and again on the server; return the save promise so failures show in the cell.
Don’t
- Don’t use a grid for a short, read-only list — use Table.
- Don’t group by a column with a different value in almost every row.