DataTable
La cuadrícula de una consola de datos: miles de filas que se desplazan con suavidad, columnas que puedes ordenar, filtrar, ensanchar y ocultar, filas para seleccionar y trabajar juntas, valores que se editan ahí mismo y exportación a CSV. En el celular cada fila se vuelve una tarjeta, y las listas largas siempre se paginan.
import { DataTable, DataTableSkeleton } from '@sypnia/ui/react'
10.000 filas
Desplázate, ordena por una columna, abre «Filtros», oculta columnas o exporta a CSV lo que ves. La barra bajo las filas las pagina: 100 a la vez, o las que elijas.
Código
import { useMemo } from 'react';
import { Badge, DataTable, useSypnia, type DataColumn } from '@sypnia/ui/react';
import { orders, statuses, type Order } from './data';
const tone = { Paid: 'ok', Pending: 'warn', Refunded: 'neutral', Failed: 'fail' } as const;
// 10,000 orders in the browser. Only the rows on screen are drawn, so it scrolls smoothly; the bar under the rows pages them.
// Sort by any column, filter by customer, status or country, show the hidden «Country» and «Items» columns, and export what you see as CSV.
export default function TenThousand() {
const { format } = useSypnia();
const rows = useMemo(() => orders(10000), []);
const columns: DataColumn<Order>[] = [
{ id: 'id', header: 'Order', machine: true, width: 120, value: (o) => o.id, sortable: true },
{ id: 'customer', header: 'Customer', width: 180, value: (o) => o.customer, sortable: true, filter: 'text' },
{ id: 'status', header: 'Status', width: 120, value: (o) => o.status, sortable: true, filter: 'select', options: statuses,
render: (o) => <Badge tone={tone[o.status as keyof typeof tone]} dot>{o.status}</Badge> },
{ id: 'country', header: 'Country', width: 150, value: (o) => o.country, sortable: true, filter: 'select',
options: ['Argentina', 'Chile', 'Colombia', 'Japan', 'Mexico', 'Peru', 'Spain', 'United States'] },
{ id: 'items', header: 'Items', numeric: true, width: 80, value: (o) => o.items, sortable: true },
{ id: 'placed', header: 'Placed', width: 120, value: (o) => o.placed, render: (o) => format.date(o.placed), sortable: true },
{ id: 'total', header: 'Total', numeric: true, width: 120, value: (o) => o.total, render: (o) => (o.total === null ? null : format.currency(o.total, 'USD')), sortable: true },
];
return <DataTable label="Orders" columns={columns} rows={rows} rowKey={(o) => o.id} columnPicker defaultHidden={['country', 'items']} exportName="orders" height="28rem" />;
} Editar ahí mismo
Haz doble clic en un valor, o llega a él y pulsa Enter. Guardar tarda un momento. Prueba un precio negativo: se rechaza y la celda dice por qué.
Código
import { useState } from 'react';
import { DataTable, type DataColumn } from '@sypnia/ui/react';
interface Plan { id: string; name: string; price: number; seats: number; status: string }
const start: Plan[] = [
{ id: 'starter', name: 'Starter', price: 9, seats: 3, status: 'Active' },
{ id: 'team', name: 'Team', price: 29, seats: 10, status: 'Active' },
{ id: 'business', name: 'Business', price: 99, seats: 50, status: 'Draft' },
{ id: 'legacy', name: 'Legacy 2024', price: 19, seats: 5, status: 'Archived' },
];
// Double-click a cell, or move to it and press Enter. Enter saves, Escape cancels, Tab saves and opens the next one.
// Saving takes a moment (the cell shows it is busy). A negative price is refused: the cell keeps what you typed and says why.
export default function Editable() {
const [plans, setPlans] = useState(start);
const save = (plan: Plan, column: string, value: unknown) => new Promise<void>((resolve, reject) => {
setTimeout(() => {
if (column === 'price' && Number(value) < 0) return reject(new Error('A price cannot be below zero.'));
setPlans((all) => all.map((p) => (p.id === plan.id ? { ...p, [column]: column === 'name' || column === 'status' ? value : Number(value) } : p)));
resolve();
}, 700);
});
const columns: DataColumn<Plan>[] = [
{ id: 'id', header: 'ID', machine: true, width: 120, value: (p) => p.id },
{ id: 'name', header: 'Name', width: 180, value: (p) => p.name, editable: true },
{ id: 'price', header: 'Price (USD)', numeric: true, width: 130, value: (p) => p.price, editable: true, editor: 'number' },
{ id: 'seats', header: 'Seats', numeric: true, width: 100, value: (p) => p.seats, editable: (p) => p.status !== 'Archived', editor: 'number' },
{ id: 'status', header: 'Status', width: 140, value: (p) => p.status, editable: true, editor: 'select', options: ['Active', 'Draft', 'Archived'] },
];
return <DataTable label="Plans" columns={columns} rows={plans} rowKey={(p) => p.id} onEdit={save} />;
} Seleccionar y actuar sobre varias
Marca filas, o la casilla del encabezado para marcar todas las que cumplen los filtros. La barra sobre las filas dice cuántas son y qué se puede hacer con todas.
Código
import { useMemo, useState } from 'react';
import { Button, DataTable, type DataColumn, type RowKey } from '@sypnia/ui/react';
import { orders, type Order } from './data';
// Tick rows, or the box in the header to tick every row that matches the filters. A bar appears with what can be done to all of them.
export default function Selectable() {
const [rows, setRows] = useState(() => orders(240));
const [selected, setSelected] = useState<Set<RowKey>>(new Set());
const columns: DataColumn<Order>[] = useMemo(() => [
{ id: 'id', header: 'Order', machine: true, width: 130, value: (o) => o.id },
{ id: 'customer', header: 'Customer', width: 200, value: (o) => o.customer, filter: 'text' },
{ id: 'status', header: 'Status', width: 120, value: (o) => o.status, filter: 'select', options: ['Paid', 'Pending', 'Refunded', 'Failed'] },
{ id: 'total', header: 'Total', numeric: true, width: 120, value: (o) => o.total },
], []);
return (
<DataTable label="Orders to review" columns={columns} rows={rows} rowKey={(o) => o.id} pageSize={50} height="24rem"
selectable selected={selected} onSelect={setSelected}
bulkActions={(keys) => (
<>
<Button size="sm" icon="check" onClick={() => { setRows((all) => all.map((o) => (keys.includes(o.id) ? { ...o, status: 'Paid' } : o))); setSelected(new Set()); }}>Mark as paid</Button>
<Button size="sm" variant="danger" icon="trash" onClick={() => { setRows((all) => all.filter((o) => !keys.includes(o.id))); setSelected(new Set()); }}>Delete</Button>
</>
)} />
);
} Como tarjetas
Lo que se ve en un celular, forzado aquí con layout='cards': 25 tarjetas por página, cada valor con el nombre de su columna.
- ord_100080
- Customer
- Status
- Paid
- Total
- 364,69 US$
- ord_100079
- Customer
- Status
- Paid
- Total
- 271,43 US$
- ord_100078
- Customer
- Status
- Paid
- Total
- 187,12 US$
- ord_100077
- Customer
- Status
- Pending
- Total
- 233,95 US$
- ord_100076
- Customer
- Status
- Refunded
- Total
- 461,58 US$
- ord_100075
- Customer
- Status
- Paid
- Total
- 454,17 US$
- ord_100074
- Customer
- Status
- Paid
- Total
- 76,29 US$
- ord_100073
- Customer
- Status
- Paid
- Total
- 278,69 US$
- ord_100072
- Customer
- Status
- Pending
- Total
- 280,32 US$
- ord_100071
- Customer
- Status
- Paid
- Total
- 27,44 US$
- ord_100070
- Customer
- Status
- Paid
- Total
- 257,43 US$
- ord_100069
- Customer
- Status
- Paid
- Total
- 211,98 US$
- ord_100068
- Customer
- Status
- Paid
- Total
- 453,25 US$
- ord_100067
- Customer
- Status
- Paid
- Total
- 258,12 US$
- ord_100066
- Customer
- Status
- Paid
- Total
- 354,12 US$
- ord_100065
- Customer
- Status
- Paid
- Total
- 195,72 US$
- ord_100064
- Customer
- Status
- Pending
- Total
- 38,86 US$
- ord_100063
- Customer
- Status
- Paid
- Total
- 110,00 US$
- ord_100062
- Customer
- Status
- Paid
- Total
- 68,90 US$
- ord_100061
- Customer
- Status
- Refunded
- Total
- 453,88 US$
- ord_100060
- Customer
- Status
- Pending
- Total
- 38,02 US$
- ord_100059
- Customer
- Status
- Paid
- Total
- 244,68 US$
- ord_100058
- Customer
- Status
- Paid
- Total
- 186,97 US$
- ord_100057
- Customer
- Status
- Refunded
- Total
- 456,50 US$
- ord_100056
- Customer
- Status
- Paid
- Total
- 94,07 US$
Código
import { useMemo } from 'react';
import { DataTable, useSypnia, type DataColumn } from '@sypnia/ui/react';
import { orders, type Order } from './data';
// On a phone (40rem and below) every row is a card, with no setting: the first column is the title and each value
// carries its column name. 25 cards a page. Here it is forced with layout="cards", so you can see it on any screen.
export default function Cards() {
const { format } = useSypnia();
const rows = useMemo(() => orders(80), []);
const columns: DataColumn<Order>[] = [
{ id: 'id', header: 'Order', machine: true, value: (o) => o.id },
{ id: 'customer', header: 'Customer', value: (o) => o.customer, editable: true },
{ id: 'status', header: 'Status', value: (o) => o.status },
{ id: 'total', header: 'Total', numeric: true, value: (o) => o.total, render: (o) => (o.total === null ? null : format.currency(o.total, 'USD')) },
];
return <DataTable layout="cards" label="Orders" columns={columns} rows={rows} rowKey={(o) => o.id} selectable onEdit={() => {}} />;
} Páginas desde un servidor
La tabla muestra la página que recibe, con filas skeleton mientras llega la siguiente, y avisa el orden y la página.
Código
import { useEffect, useState } from 'react';
import { DataTable, type DataColumn, type DataSort } from '@sypnia/ui/react';
import { orders, type Order } from './data';
const all = orders(1342);
// A pretend server: it sorts and cuts the page, and answers after a moment.
function fetchPage(page: number, size: number, sort: DataSort | null) {
return new Promise<Order[]>((resolve) => setTimeout(() => {
const list = sort ? [...all].sort((a, b) => String(a[sort.id as keyof Order]).localeCompare(String(b[sort.id as keyof Order]), undefined, { numeric: true }) * (sort.dir === 'ascending' ? 1 : -1)) : all;
resolve(list.slice((page - 1) * size, page * size));
}, 600));
}
// When the rows live on a server, pass server and pagination: the table shows what it is given and reports the sort and the page.
export default function ServerPages() {
const [page, setPage] = useState(1);
const [size, setSize] = useState(25);
const [sort, setSort] = useState<DataSort | null>(null);
const [rows, setRows] = useState<Order[] | undefined>();
useEffect(() => { let live = true; setRows(undefined); fetchPage(page, size, sort).then((r) => live && setRows(r)); return () => { live = false; }; }, [page, size, sort]);
const columns: DataColumn<Order>[] = [
{ id: 'id', header: 'Order', machine: true, width: 130, value: (o) => o.id, sortable: true },
{ id: 'customer', header: 'Customer', width: 200, value: (o) => o.customer, sortable: true },
{ id: 'placed', header: 'Placed', width: 130, value: (o) => o.placed, sortable: true },
{ id: 'total', header: 'Total', numeric: true, width: 120, value: (o) => o.total, sortable: true },
];
return (
<DataTable server label="Orders" columns={columns} rows={rows} loading={!rows} rowKey={(o) => o.id} height="22rem"
sort={sort} onSort={(s) => { setSort(s); setPage(1); }}
pagination={{ page, pageSize: size, total: all.length, onPage: setPage, onPageSize: (n) => { setSize(n); setPage(1); } }} />
);
} Cargando, error y vacía
Elige un estado. «Intentar de nuevo» y «Crear una clave» te llevan a las filas.
Código
import { useState } from 'react';
import { Button, DataTable, EmptyState, SegmentedControl, type DataColumn } from '@sypnia/ui/react';
interface Key { id: string; name: string; created: string }
const columns: DataColumn<Key>[] = [
{ id: 'name', header: 'Name', value: (k) => k.name },
{ id: 'id', header: 'Key', machine: true, value: (k) => k.id },
{ id: 'created', header: 'Created', value: (k) => k.created },
];
const keys: Key[] = [{ id: 'sk_live_4f1a…9c2e', name: 'Back office', created: '2026-11-02' }];
// Loading draws skeleton rows with the real columns, never a spinner. An error says what happened and offers to try again.
// An empty table says what goes in it and the first step.
export default function States() {
const [state, setState] = useState('loading');
return (
<div className="sy-stack">
<SegmentedControl label="State" value={state} onChange={setState}
options={[{ value: 'loading', label: 'Loading' }, { value: 'error', label: 'Error' }, { value: 'empty', label: 'Empty' }, { value: 'ready', label: 'Ready' }]} />
<DataTable label="API keys" columns={columns} rowKey={(k) => k.id}
rows={state === 'ready' ? keys : state === 'empty' ? [] : undefined} loading={state === 'loading'}
error={state === 'error' ? 'The keys could not be loaded. The server did not answer in time.' : undefined} onRetry={() => setState('ready')}
empty={<EmptyState icon="key" title="No keys yet" actions={<Button variant="primary" icon="plus" onClick={() => setState('ready')}>Create a key</Button>}>A key lets your server talk to Sypnia without a password.</EmptyState>} />
</div>
);
} Skeleton
Antes de saber siquiera las columnas: las mismas cajas que la tabla real, así nada se mueve cuando llegan los datos. En el celular, tarjetas.
Código
import { DataTableSkeleton } from '@sypnia/ui/react';
// Before even the columns are known: toolbar, header, rows and the pagination bar on wide screens, and cards on phones,
// in the same boxes as a real DataTable. When the columns are known, use <DataTable loading> instead.
export default function Skeleton() {
return <DataTableSkeleton columns={5} rows={6} selectable />;
} Cuándo usarlo
Úsalo cuando
- La gente trabaja con las filas, no solo las lee: busca algunas, cambia valores, actúa sobre varias a la vez.
- Hay cientos o miles de filas: solo se dibujan las que están en pantalla.
- Las filas viven en un servidor: pasa
serverypagination, y la tabla avisa el orden, los filtros y la página. - Dale a cada columna un
value: es lo que ordena, filtra, se edita y va al CSV.rendersolo cambia cómo se ve.
No lo uses cuando
- La gente solo lee unas pocas filas: Table es más liviana y basta.
- Son datos de una sola cosa: KeyValue.
- Cada elemento tiene otra forma o una imagen: Cards.
Para todos
- Es una cuadrícula con nombre (
label) y una sola parada del tabulador. Las flechas mueven entre celdas, Inicio y Fin van a los extremos de la fila, Re Pág y Av Pág mueven una pantalla. - Enter edita la celda, Enter o Tab la guardan, Escape cancela. Mientras guarda, la celda queda ocupada; si falla, conserva lo escrito y dice por qué.
- Un encabezado que ordena es un botón llamado «Ordenar por Total», y la columna dice cómo está ordenada. El borde de una columna se ensancha con las flechas.
- Los valores vacíos se escriben NULL, así «nada» nunca parece un texto vacío.
- Mientras carga dibuja filas skeleton con las columnas reales, nunca un spinner. Se anuncian las filas y las seleccionadas.
- En el celular (40rem o menos) cada fila es una tarjeta: cada valor lleva el nombre de su columna, y la casilla y los botones de editar miden al menos 44 px.
Props
| DataTable | Tipo | Por defecto |
|---|---|---|
columnsobligatorio | DataColumn<Row>[] | |
labelobligatorioA name for screen readers. | string | |
rowKeyobligatorio | (row: Row) => RowKey | |
rowsobligatorioThe rows in memory: all of them (the table scrolls through thousands), or one page when `pagination` is set. | Row[] | undefined | |
bulkActionsButtons for the bar that appears while rows are selected. Receives the selected keys and the selected rows that are in memory. | ((keys: RowKey[], rows: Row[]) => ReactNode) | |
columnPickerAdds the «Columns» menu to the toolbar. | boolean | |
defaultHiddenIds of columns hidden at first. With `columnPicker` the person can change them. | string[] | |
defaultSort | DataSort | null | null |
emptyWhat to show when there are no rows at all: an EmptyState with the next step. | ReactNode | |
errorSomething failed: say what happened in plain words. | ReactNode | |
exportNameAdds «Export CSV» to the toolbar. This is the name of the file. It exports the selected rows, or all the rows shown. | string | |
filtersControlled filters, by column id. Leave it out and the table keeps its own. | DataFilters | |
heightThe tallest the grid gets before it scrolls: any CSS length. | string | min(32rem, 70dvh) |
layout`auto`: a grid on wide screens, cards on phones. Force one of them for a narrow panel or a preview. | "grid" | "cards" | "auto" | auto |
loadingData is on its way: rows are drawn as skeletons of the right shape. | boolean | |
loadingRowsHow many skeleton rows (cards on phones) to draw while loading: as many as will come. Default 8 rows, 3 cards. Or the rows of the last visit: as many, and on phones each card's values that can be edited wait in their edit box (an `editable` function is asked about each of them). | number | Row[] | |
onColumnWidthsCalled with every width, by column id, after the person resizes one. | ((widths: Record<string, number>) => void) | |
onEditSaves one value. Return a promise and the cell shows it is busy; reject it (or throw) and the cell keeps what was typed and shows the reason. | ((row: Row, columnId: string, value: unknown) => void | Promise<unknown>) | |
onFilter | ((filters: DataFilters) => void) | |
onRetryWith `error`: shows «Try again». | (() => void) | |
onSelect | ((selected: Set<RowKey>) => void) | |
onSort | ((sort: DataSort | null) => void) | |
pageSizeRows in memory are shown a page at a time (every table paginates). The person can change it. On phones a page holds at most 25 cards. | number | 100 |
pageSizesThe page sizes the person can choose from. | number[] | [50, 100, 250, 500] |
paginationServer pages: the table shows `rows` as one page and this bar under them. Without it the table pages the rows in memory itself (`pageSize`). | { page: number; pageSize: number; total: number; onPage: (page: number) => void; onPageSize?: ((size: number) => void); } | |
selectableAdds a checkbox to every row. | boolean | |
selectedControlled selection: the keys of the selected rows. | ReadonlySet<RowKey> | |
serverThe rows already arrive sorted and filtered (by a server): the table only reports what the person asked through `onSort` and `onFilter`. | boolean | |
sortControlled sort. Leave it out and the table keeps its own. | DataSort | null | |
toolbarExtra content at the start of the toolbar: a search field, a title. | ReactNode |
| DataTableSkeleton | Tipo | Por defecto |
|---|---|---|
columns | number | 5 |
layout | "grid" | "cards" | "auto" | auto |
pagination | boolean | true |
rows | number | 8 |
selectable | boolean | |
toolbar | boolean | true |