Skip to Content
Cristal

Data

Table

A table whose columns each user can arrange.

<cr-table>CrTable

Example

Each user arranges the table to their liking: drag a header to move the column, drag the right edge of a header to change its width (double-click to fit it to the content), choose the displayed columns in "Columns" and the row height with "Comfortable", "Normal" or "Compact". "Reset" goes back to the initial layout.

'use client';

import { useState } from 'react';
import { CrSelect, CrTable } from '@cristal-ui/react';

const columns = [
  { key: 'amount', label: 'Amount', width: 120, align: 'end' as const, pinned: true },
  {
    key: 'status',
    label: 'Status',
    width: 150,
    badges: { Paid: 'success' as const, Shipped: 'primary' as const, Pending: 'warning' as const, Refunded: 'danger' as const },
  },
  { key: 'channel', label: 'Channel', width: 120 },
  { key: 'region', label: 'Region', width: 110 },
  { key: 'product', label: 'Product', width: 260 },
  { key: 'units', label: 'Units', width: 100, align: 'end' as const },
];

const rows = [
  { amount: '$1,240.50', status: 'Paid', channel: 'Web', region: 'North', product: 'Height-adjustable desk', units: 2 },
  { amount: '$318.00', status: 'Shipped', channel: 'Store', region: 'Central', product: 'Swing-arm desk lamp', units: 4 },
  { amount: '$4,860.00', status: 'Pending', channel: 'Wholesale', region: 'Coast', product: 'Ergonomic chair', units: 12 },
  { amount: '$189.90', status: 'Paid', channel: 'App', region: 'South', product: 'Modular wall shelf', units: 1 },
  { amount: '$540.00', status: 'Refunded', channel: 'Web', region: 'East', product: 'Folding oak table', units: 2 },
  { amount: '$772.40', status: 'Shipped', channel: 'Store', region: 'North', product: 'Workbench with drawers', units: 1 },
];

const variants = ['default', 'striped', 'cards', 'minimal', 'grid'] as const;

export default function TableOrders() {
  const [variant, setVariant] = useState<(typeof variants)[number]>('default');

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, width: '100%' }}>
      <CrSelect label="Style" value={variant} onCrChange={(event) => setVariant(event.detail as typeof variant)} style={{ maxWidth: 220 }}>
        {variants.map((name) => (
          <option key={name} value={name}>
            {name}
          </option>
        ))}
      </CrSelect>
      <CrTable label="This week's orders" variant={variant} columns={columns} rows={rows} storageKey="docs-commandes-en" />
    </div>
  );
}

Styles

The variant property changes the look of the table; pick one in the example above:

ValueLook
defaulttinted header, thin lines between rows, light shadow (default)
stripedalternating rows, no lines
cardseach row is a card laid on a tinted background, with a purple border on hover
minimalno frame or header background, a bold line under the titles
gridevery cell has a border, spreadsheet-style; the hovered cell is outlined

Headers stay stuck at the top when the table scrolls: set its height with the --cr-table-max-height CSS variable (for example 400px).

Status badges

With badges, a column displays some values as colored badges: { Paid: 'success', Pending: 'warning' }. Available tones: primary, success, warning, danger, neutral. The text stays readable (contrast of at least 4.5:1) and color is never the only information: the value is always written out.

Columns and rows

columns describes the columns, in their initial order:

FieldDescription
keykey of the value in each row (required)
labelcolumn title (required)
widthwidth in pixels, 160 by default (from 64 to 640)
alignend to right-align, for example amounts
pinnedcolumn pinned to the left, which stays visible when the table scrolls
hiddencolumn hidden initially
badgesvalues displayed as badges, with their tone
sortablethe header sorts the rows
format(value, row) => text function for display; sorting keeps the raw value
primarythe cell becomes the row's button (see "Sort, select, open")
slotthe cell displays your own elements (buttons, menus, links)

rows is an array of objects, with one value per key. Without format, values are displayed as text.

Sort, select, open

RestockRestockRestockRestockRestock

0 rows checked · last action: —

'use client';

import { useState } from 'react';
import { CrButton, CrTable } from '@cristal-ui/react';

const dollars = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });

const columns = [
  { key: 'name', label: 'Product', width: 220, sortable: true, primary: true },
  { key: 'quantity', label: 'Quantity', width: 130, align: 'end' as const, sortable: true },
  { key: 'price', label: 'Price', width: 130, align: 'end' as const, sortable: true, format: (value: unknown) => dollars.format(value as number) },
  { key: 'actions', label: 'Actions', width: 150, slot: true },
];

const rows = [
  { id: 1, name: '27-inch monitor', quantity: 12, price: 329 },
  { id: 2, name: 'USB-C cable', quantity: 140, price: 9.9 },
  { id: 3, name: 'Mechanical keyboard', quantity: 0, price: 89 },
  { id: 4, name: 'Wireless mouse', quantity: 45, price: 24.5 },
  { id: 5, name: 'Headphones', quantity: 8, price: 1290 },
];

export default function TableStock() {
  const [selected, setSelected] = useState<unknown[]>([]);
  const [last, setLast] = useState('—');

  return (
    <div style={{ display: 'grid', gap: 12, width: '100%' }}>
      <CrTable
        label="Stock"
        columns={columns}
        rows={rows}
        selectable
        selected={selected}
        onCrSelectionChange={(event) => setSelected(event.detail)}
        onCrRowClick={(event) => setLast(`open ${event.detail.name}`)}
      >
        {rows.map((row) => (
          <CrButton key={row.id} slot={`actions-${row.id}`} size="xs" variant="outline" onClick={() => setLast(`restock ${row.name}`)}>
            Restock
          </CrButton>
        ))}
      </CrTable>
      <p>
        {selected.length} {selected.length === 1 ? 'row' : 'rows'} checked · last action: {last}
      </p>
    </div>
  );
}
  • Sort: with sortable, clicking the header (or pressing S) sorts in ascending order, then descending, then back to the original order. Numbers and dates compare by value, text in the language's order ("10" after "9"); empty cells stay at the bottom. Keep raw values in rows (numbers, dates) and format them with format, so that $1,290 comes after $329. The current sort is in sort ({ key, direction: 'ascending' | 'descending' }), and onCrSortChange gives it on each change.
  • Select: selectable adds a box per row and a "select all" box (half-checked when only some rows are). selected holds the rowKey values (id by default) of the checked rows; onCrSelectionChange gives the new list.
  • Open a row: the primary column shows a button per row; clicking it, or anywhere else on the row, emits onCrRowClick with the row. Checkboxes, buttons and links in the row keep their own action.
  • Custom cells: for a slot column, put one child with slot="<key>-<id>" per row inside the table, for example slot="actions-3". Only displayed rows show their content.

Large datasets

The table first renders 100 rows, then 100 more each time its end gets close to the screen while scrolling: thousands of rows display without freezing the page. The total is still announced (aria-rowcount) and a line below the table reads "100 of 3,685 rows: more appear as you scroll.". When rows changes (a filter, another period), the display starts again from the first 100.

Remembering settings

With storageKey, the settings (order, widths, pinned and hidden columns, density) are saved in the browser and restored on the next visit. onCrLayoutChange also gives them in event.detail on every change, to save them on the server for example.

Keyboard

Move focus to a header with Tab:

KeyAction
← →adjacent header
Home / Endfirst / last header
Alt + ← →moves the column
Shift + ← →narrows or widens the column by 16 pixels
Enterfits the width to the content
Fpins the column to the left, or unpins it
Mhides the column
Ssorts the column, if it is sortable

The table footer recalls these shortcuts and summarizes the layout: "6 of 7 columns · 1 pinned · normal rows".

Animations

  • The grabbed column floats above the others, and a purple line shows where it will be dropped.
  • After a move, each column slides from its old position to the new one.
  • A shadow appears under pinned columns as soon as the table scrolls.

If the user has asked their system to reduce motion, columns change position without sliding.

Accessibility

  • It is a real table (table, th scope="col"), named by its title.
  • Every mouse setting has a keyboard equivalent, described on each header.
  • Every action is announced: "Status moved to position 3 of 7.", "Product pinned to the left.", "Region hidden: 6 of 7 columns.".
  • A pinned column is announced as "pinned"; at least one column always stays visible.
  • With many rows, the total number is announced even if only the first ones are displayed.
  • The sorted column carries aria-sort; each sort is announced: "Sorted by Price, ascending.".
  • Each selection box is named after its row ("Select USB-C cable") and the number of checked rows is announced.
  • A clickable row always has a real button, reachable with Tab: clicking the row is only a mouse shortcut.

API

Properties

PropertyTypeDefaultDescription
columnsTableColumn[][]Colonnes : key, label, width (px, 160 par défaut), align ('start' ou 'end'), pinned, hidden, badges, sortable, format, primary, slot.
density"comfortable" | "compact" | "normal"'normal'Hauteur des lignes.
label (obligatoire)string—Titre du tableau.
rowKeystring'id'Champ des lignes qui les identifie : sélection et cellules slot.
rowsRecord<string, unknown>[][]Lignes : un objet par ligne, avec une valeur par clé de colonne.
selectablebooleanfalseAjoute une case à cocher par ligne et une case « tout sélectionner ».
selectedunknown[][]Lignes cochées : leurs valeurs de rowKey.
sortTableSort—Tri en cours : { key, direction: 'ascending' | 'descending' } ; absent pour l'ordre d'origine.
storageKeystring—Clé localStorage : les réglages de l'utilisateur sont retenus d'une visite à l'autre.
variant"cards" | "default" | "grid" | "minimal" | "striped"'default'Style : default, striped (lignes alternées), cards (lignes en cartes), minimal ou grid (façon tableur).

Events

Reactevent.detailDescription
onCrLayoutChangeTableLayoutÉmis à chaque réglage ; detail : les colonnes (ordre, largeur, fixée, masquée) et la densité.
onCrRowClickstring | unknownÉmis au clic sur la cellule primary ou ailleurs sur la ligne ; detail : la ligne.
onCrSelectionChangeunknown[]Émis quand une case est cochée ou décochée ; detail : les valeurs de rowKey des lignes cochées.
onCrSortChangeTableSortÉmis au changement de tri ; detail : le tri, ou null pour l'ordre d'origine.

CSS parts

To style it from outside: cr-table::part(name) { … }

PartDescription
columnsLe panneau « Colonnes ».

On this page