Skip to content

EditableTable

A table people work in: each cell they may change is edited in place, saving shows in the cell, and a refused value stays with its reason. Rows are added at the top, ticked rows are changed together, and the table goes to CSV.

import { DataTable } from '@sypnia/ui/react'

On this page
  1. On a desktop
  2. On a phone
  3. Empty
  4. Skeleton
  5. When the rows cannot load
  6. When to use it
  7. For everyone
  8. Props

On a desktop

Double-click a price and type a negative number: it is refused. Tick rows to archive them (with Undo) or delete them. Add a row, hide columns, export.

products

The table products of northwind-shop. Double-click a cell to change it.

Import CSV
Status
NW-1001
Oak desk lamp
$48.00
120
Active
NW-1002
Linen cushion
$22.00
340
Active
NW-1003
Stoneware mug, set of 4
$36.00
0
Active
NW-1004
Walnut side table
$210.00
14
Active
NW-1005
Wool throw
$89.00
57
Draft
NW-1006
Brass wall hook
$12.00
800
Active
NW-1007
Rattan basket
$31.00
96
Active
NW-1008
Ceramic vase
$44.00
23
Archived
NW-1009
Cotton apron
$19.00
210
Active
NW-1010
Pine bookshelf
$160.00
8
Draft
NW-1011
Glass carafe
$27.00
150
Active
NW-1012
Jute rug, 2×3 m
$240.00
5
Active
12 rows · 0 selected
Code
import { useMemo, useState } from 'react';
import {
  Badge, Button, ConfirmDialog, DataTable, EmptyState, Page, PageHeader, SkeletonOf, SkeletonWords, Toaster, toast, useSypnia, type DataColumn, type RowKey,
} from '@sypnia/ui/react';

// A table people work in: every cell they may change is edited in place (double-click, or Enter), saving shows in the
// cell, and a refused value stays with its reason. Rows are added at the top, ticked rows are changed or deleted
// together, and the whole table goes to CSV. On phones each row is a card.
const en = {
  title: 'products', lead: 'The table products of northwind-shop. Double-click a cell to change it.', add: 'Add row', import: 'Import CSV',
  sku: 'SKU', name: 'Name', price: 'Price', stock: 'Stock', status: 'Status', statuses: ['Active', 'Draft', 'Archived'],
  newName: 'New product', added: 'Row added at the top. Give it a name and a price.', negative: 'A price cannot be below zero.', noStock: 'Stock must be a whole number, 0 or more.',
  archive: 'Archive', del: 'Delete', delQ: (n: number) => (n === 1 ? 'Delete 1 row?' : `Delete ${n} rows?`), delBody: 'They leave the table products now. Orders that point to them keep their copy of the name and price.',
  deleted: (n: number) => (n === 1 ? '1 row deleted' : `${n} rows deleted`), archived: (n: number) => (n === 1 ? '1 row archived' : `${n} rows archived`), undo: 'Undo',
  emptyTitle: 'products has no rows yet', emptyBody: 'Add the first one here, import a CSV, or write to it from your app: every row appears here at once.',
  failed: 'The rows of products could not be loaded. The table and its data are safe.',
};
const es: typeof en = {
  title: 'products', lead: 'La tabla products de northwind-shop. Haz doble clic en una celda para cambiarla.', add: 'Agregar fila', import: 'Importar CSV',
  sku: 'SKU', name: 'Nombre', price: 'Precio', stock: 'Existencias', status: 'Estado', statuses: ['Activo', 'Borrador', 'Archivado'],
  newName: 'Producto nuevo', added: 'Fila agregada arriba. Ponle un nombre y un precio.', negative: 'Un precio no puede ser menor que cero.', noStock: 'Las existencias deben ser un número entero, 0 o más.',
  archive: 'Archivar', del: 'Borrar', delQ: (n: number) => (n === 1 ? '¿Borrar 1 fila?' : `¿Borrar ${n} filas?`), delBody: 'Salen ya de la tabla products. Los pedidos que las usan conservan su copia del nombre y el precio.',
  deleted: (n: number) => (n === 1 ? '1 fila borrada' : `${n} filas borradas`), archived: (n: number) => (n === 1 ? '1 fila archivada' : `${n} filas archivadas`), undo: 'Deshacer',
  emptyTitle: 'products aún no tiene filas', emptyBody: 'Agrega la primera aquí, importa un CSV, o escribe desde tu app: cada fila aparece aquí al instante.',
  failed: 'No se pudieron cargar las filas de products. La tabla y sus datos están a salvo.',
};
interface Product { sku: string; name: string; price: number; stock: number; status: number }
const seed: Product[] = [
  ['NW-1001', 'Oak desk lamp', 48, 120, 0], ['NW-1002', 'Linen cushion', 22, 340, 0], ['NW-1003', 'Stoneware mug, set of 4', 36, 0, 0],
  ['NW-1004', 'Walnut side table', 210, 14, 0], ['NW-1005', 'Wool throw', 89, 57, 1], ['NW-1006', 'Brass wall hook', 12, 800, 0],
  ['NW-1007', 'Rattan basket', 31, 96, 0], ['NW-1008', 'Ceramic vase', 44, 23, 2], ['NW-1009', 'Cotton apron', 19, 210, 0],
  ['NW-1010', 'Pine bookshelf', 160, 8, 1], ['NW-1011', 'Glass carafe', 27, 150, 0], ['NW-1012', 'Jute rug, 2×3 m', 240, 5, 0],
].map(([sku, name, price, stock, status]) => ({ sku, name, price, stock, status }) as Product);
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));

export default function EditableTable({ state = 'ready' }: { state?: 'ready' | 'loading' | 'empty' | 'error' }) {
  const { locale, format } = useSypnia();
  const c = locale.startsWith('es') ? es : en;
  const [rows, setRows] = useState<Product[]>(state === 'empty' ? [] : seed);
  const [selected, setSelected] = useState<Set<RowKey>>(new Set());
  const [confirm, setConfirm] = useState<string[] | null>(null);
  const [failed, setFailed] = useState(state === 'error');
  const [next, setNext] = useState(1013);
  const tones = ['ok', 'neutral', 'warn'] as const;
  // Loading: the real table, toolbar and columns; as many rows as the last visit, each value as long as a real one.
  const columns: DataColumn<Product>[] = useMemo(() => [
    { id: 'sku', header: c.sku, icon: 'primary-key', machine: true, width: 120, value: (p) => p.sku, sortable: true, skeleton: (i) => <SkeletonWords>{seed[i % seed.length].sku}</SkeletonWords> },
    { id: 'name', header: c.name, width: 240, value: (p) => p.name, editable: true, sortable: true, filter: 'text', skeleton: (i) => <SkeletonWords>{seed[i % seed.length].name}</SkeletonWords> },
    { id: 'price', header: c.price, note: 'USD', numeric: true, width: 120, value: (p) => p.price, render: (p) => format.currency(p.price, 'USD'), editable: true, editor: 'number', sortable: true,
      skeleton: (i) => <SkeletonWords>{format.currency(seed[i % seed.length].price, 'USD')}</SkeletonWords> },
    { id: 'stock', header: c.stock, numeric: true, width: 120, value: (p) => p.stock, editable: (p) => p.status !== 2, editor: 'number', sortable: true,
      skeleton: (i) => <SkeletonWords>{seed[i % seed.length].stock}</SkeletonWords> },
    { id: 'status', header: c.status, width: 140, value: (p) => c.statuses[p.status], render: (p) => <Badge tone={tones[p.status]} dot>{c.statuses[p.status]}</Badge>,
      editable: true, editor: 'select', options: c.statuses, filter: 'select', skeleton: (i) => <SkeletonOf><Badge dot>{c.statuses[seed[i % seed.length].status]}</Badge></SkeletonOf> },
  ], [c, format]); // eslint-disable-line react-hooks/exhaustive-deps
  const save = async (p: Product, col: string, value: unknown) => {
    await wait(500);
    if (col === 'price' && Number(value) < 0) throw new Error(c.negative);
    if (col === 'stock' && (!Number.isInteger(Number(value)) || Number(value) < 0)) throw new Error(c.noStock);
    const v = col === 'status' ? c.statuses.indexOf(String(value)) : col === 'name' ? String(value) : Number(value);
    setRows((all) => all.map((r) => (r.sku === p.sku ? { ...r, [col]: v } : r)));
  };
  const add = () => { setRows((all) => [{ sku: `NW-${next}`, name: c.newName, price: 0, stock: 0, status: 1 }, ...all]); setNext((n) => n + 1); toast(c.added); };
  const toolbar = <><Button size="sm" icon="upload" href="#csv-import">{c.import}</Button><Button size="sm" variant="primary" icon="plus" onClick={add}>{c.add}</Button></>;
  return (
    <Page wide>
      <PageHeader title={c.title} lead={c.lead} />
      <DataTable label={c.title} columns={columns} rows={state === 'loading' ? undefined : rows} loading={state === 'loading'} loadingRows={seed} rowKey={(p) => p.sku}
        onEdit={save} selectable selected={selected} onSelect={setSelected} columnPicker exportName="products" pageSize={25} toolbar={toolbar}
        error={failed ? c.failed : undefined} onRetry={() => setFailed(false)}
        empty={<EmptyState icon="table" compact title={c.emptyTitle} actions={toolbar}>{c.emptyBody}</EmptyState>}
        bulkActions={(keys) => (
          <>
            <Button size="sm" icon="archive" onClick={() => {
              const before = rows;
              setRows((all) => all.map((r) => (keys.includes(r.sku) ? { ...r, status: 2 } : r))); setSelected(new Set());
              toast(c.archived(keys.length), { action: { label: c.undo, onClick: () => setRows(before) } });
            }}>{c.archive}</Button>
            <Button size="sm" variant="danger" icon="trash" onClick={() => setConfirm(keys.map(String))}>{c.del}</Button>
          </>
        )} />
      <ConfirmDialog open={confirm !== null} title={c.delQ(confirm?.length ?? 0)} action={c.del} onClose={() => setConfirm(null)}
        onConfirm={() => { setRows((all) => all.filter((r) => !confirm!.includes(r.sku))); toast(c.deleted(confirm!.length), { tone: 'ok' }); setSelected(new Set()); setConfirm(null); }}>
        <p>{c.delBody}</p>
      </ConfirmDialog>
      <Toaster />
    </Page>
  );
}

On a phone

On a phone each row is a card; the actions on ticked rows sit two by two.

Empty

A table with no rows yet: three ways to fill it.

products

The table products of northwind-shop. Double-click a cell to change it.

Import CSV

products has no rows yet

Add the first one here, import a CSV, or write to it from your app: every row appears here at once.
Import CSV
0 rows · 0 selected

Skeleton

The real table, its toolbar and columns, with as many rows as the last visit; each value is a bar as long as a real one, and on phones each card keeps its edit boxes.

products

The table products of northwind-shop. Double-click a cell to change it.

Import CSV

When the rows cannot load

The table keeps its frame; the message says the data is safe and offers «Try again».

products

The table products of northwind-shop. Double-click a cell to change it.

Import CSV

When to use it

Use it when

  • The rows of a table in a data console, a list of products or prices, any list edited often.
  • Refusing a value in the cell that holds it, with the reason, and keeping what was typed.

Do not use it when

  • Editing many fields of one record: open it in a Drawer or a FormPage.
  • Deleting ticked rows without asking: say how many, and what happens to what points to them.

For everyone

  • Cells are reached with the arrow keys; Enter edits, Escape cancels, Tab saves and moves on.
  • A cell that is saving says so, and a refused value is read with its reason.
  • On phones every row is a card with its column names.

Props

DataTableTypeDefault
columnsrequired DataColumn<Row>[]
labelrequired

A name for screen readers.

string
rowKeyrequired (row: Row) => RowKey
rowsrequired

The rows in memory: all of them (the table scrolls through thousands), or one page when `pagination` is set.

Row[] | undefined
bulkActions

Buttons 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)
columnPicker

Adds the «Columns» menu to the toolbar.

boolean
defaultHidden

Ids of columns hidden at first. With `columnPicker` the person can change them.

string[]
defaultSort DataSort | null null
empty

What to show when there are no rows at all: an EmptyState with the next step.

ReactNode
error

Something failed: say what happened in plain words.

ReactNode
exportName

Adds «Export CSV» to the toolbar. This is the name of the file. It exports the selected rows, or all the rows shown.

string
filters

Controlled filters, by column id. Leave it out and the table keeps its own.

DataFilters
height

The 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
loading

Data is on its way: rows are drawn as skeletons of the right shape.

boolean
loadingRows

How 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[]
onColumnWidths

Called with every width, by column id, after the person resizes one.

((widths: Record<string, number>) => void)
onEdit

Saves 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)
onRetry

With `error`: shows «Try again».

(() => void)
onSelect ((selected: Set<RowKey>) => void)
onSort ((sort: DataSort | null) => void)
pageSize

Rows 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
pageSizes

The page sizes the person can choose from.

number[] [50, 100, 250, 500]
pagination

Server 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); }
selectable

Adds a checkbox to every row.

boolean
selected

Controlled selection: the keys of the selected rows.

ReadonlySet<RowKey>
server

The rows already arrive sorted and filtered (by a server): the table only reports what the person asked through `onSort` and `onFilter`.

boolean
sort

Controlled sort. Leave it out and the table keeps its own.

DataSort | null
toolbar

Extra content at the start of the toolbar: a search field, a title.

ReactNode
  1. On a desktop
  2. On a phone
  3. Empty
  4. Skeleton
  5. When the rows cannot load
  6. When to use it
  7. For everyone
  8. Props

    Search pages, sections and terms