# Columns

> Column definitions, widths, alignment, types and formats, visibility, resizing, reordering and auto-size.

Canonical: https://salmonui.dev/docs/data-grid/columns

Columns are plain definition objects, passed as the `columns` array or as
`<DataGridColumn>` children (nested children form stacked headers). Each one is compiled once per stable
definition and addressed by a stable column id (its `id`, else its `field`),
so state such as width, order and visibility survives data changes.

## Defining columns

A column reads a row field or computes its value from the row.
Widths accept pixels, percentages of the viewport and `auto`, with
minimum and maximum bounds that also clamp resizing. Cell and header
text align with logical directions, so alignment mirrors in RTL.

Typed columns format numbers, currency, percentages and dates
through the platform `Intl` API using the grid locale, currency and time
zone. Boolean columns can render as checkboxes. Overflowing
text is clipped, truncated with an ellipsis, or truncated with a tooltip
(`overflow: 'clip' | 'ellipsis' | 'ellipsisWithTooltip'`).
A `primaryKey` column derives the stable row id.

```tsx
import { DataGrid, type DataGridColumn } from '@salmonui/data-grid';
import '@salmonui/data-grid/styles.css';

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', type: 'number', primaryKey: true, width: 100 },
  { field: 'customer.name', header: 'Customer', width: '30%', minWidth: 160 },
  { field: 'total', header: 'Total', type: 'number', format: 'C2', align: 'end' },
  { id: 'net', header: 'Net', valueGetter: (row) => row.total - row.tax, type: 'number' },
  { field: 'shipped', header: 'Shipped', type: 'boolean', displayAsCheckbox: true },
];

<DataGrid data={orders} columns={columns} locale="en-US" currency="USD" timeZone="UTC" aria-label="Orders" />
```

### Live demo: Column definitions

Live demo: https://salmonui.dev/demos/data-grid/columns-basics

Fields and header text, px / percent / auto widths with min and max, alignment, typed and formatted values, checkbox display, computed values and overflow modes, declared as `<DataGridColumn>` children.

`Demo.tsx`:

```tsx
'use client';

import { DataGrid, DataGridColumn } from '@salmonui/data-grid';
import { createOrders, type Order } from '../../lib/fixtures';

// Module-level constants are fine: they are immutable inputs, not render state.
const orders = createOrders(500);
const lineTotal = (o: Order) => o.quantity * o.unitPrice;

// Columns as JSX children; the `columns` array prop takes the same fields.
export default function ColumnsBasicsDemo() {
  return (
    <DataGrid<Order> aria-label="Orders with typed and formatted columns" data={orders} height={420} locale="en-US" currency="USD" timeZone="UTC">
      {/* `primaryKey` derives the row id. */}
      <DataGridColumn field="id" header="Order" primaryKey width={110} />
      <DataGridColumn field="customer" header="Customer" width={160} minWidth={120} maxWidth={260} />
      <DataGridColumn field="country" header="Country" width="12%" />
      {/* typed columns with locale-aware number and date formats. */}
      <DataGridColumn field="quantity" header="Qty" type="number" format="N0" align="end" width={80} />
      <DataGridColumn field="unitPrice" header="Unit price" type="number" format="C2" align="end" headerAlign="end" width={120} />
      <DataGridColumn field="discount" header="Discount" type="number" format="P0" align="end" width={100} />
      <DataGridColumn field="placed" header="Placed" type="datetime" format="yMMMd" width={130} />
      {/* boolean column rendered as a checkbox. */}
      <DataGridColumn field="shipped" header="Shipped" type="boolean" displayAsCheckbox align="center" width={100} />
      {/* computed value through `valueGetter`. */}
      <DataGridColumn<Order> id="total" header="Line total" type="number" format="C2" align="end" width={120} valueGetter={lineTotal} />
      {/* 'auto' + overflow modes. */}
      <DataGridColumn field="note" header="Note (ellipsis with tooltip)" width="auto" overflow="ellipsisWithTooltip" />
      <DataGridColumn field="product" header="Product (clip)" width={110} overflow="clip" />
    </DataGrid>
  );
}
```

Dates are formatted on the server as well as in the browser, so a server
rendered grid must pin the time zone and locale; otherwise the two outputs
differ and hydration fails.

## Array or children, inferred types and column ids

The `columns` array and `<DataGridColumn>` children take the same fields and compile to the same stable
columns; pass one form (with both, the children win and development builds
warn).

Without `type`, a column infers it from the first non-null value of its
field: `number`, `boolean`, `string` or `date`. Rows that arrive
later resolve a pending type without recompiling the columns. When no value
decides the type, the column falls back to `string` with a development
warning; set `type` to silence it.

A column id resolves from `column.id`, then `column.field`; a column with
neither, such as a template-only column, gets a deterministic generated id
(`__col_<position>`, identical on the server and the client) and a
development warning, and a duplicate id gets a `~2` suffix. Give
such columns an `id` so state, events and methods can address them.

The instance reads the compiled columns:

| Method | Returns |
| --- | --- |
| `api.getColumn(fieldOrId)` | The column with that id, else the first with that field |
| `api.getColumns()` | Every leaf column in definition order, hidden ones included |
| `api.getVisibleColumns()` / `api.getHiddenColumns()` | Visible leaves in runtime order / hidden leaves |
| `api.getColumnAt(index)` | The visible leaf at an index (`getColumnByIndex`) |
| `api.getColumnIndex(fieldOrId)` | Its index among the visible leaves, or -1 |

## Text, markup and templates

Cell text is always text: React escapes it, so a value such as
`<b>Aiko Tan</b>` shows its angle brackets and can never inject markup.
There is no switch that renders cell values as HTML: it would add a per-cell branch and an XSS footgun
for no capability gain. Return elements from `column.renderCell` instead
of building HTML strings; for trusted HTML the
application owns the `dangerouslySetInnerHTML` call inside its template.

Templates are functions only: there are
no `${field}` string templates. `column.renderCell(ctx)` and
`column.renderHeader(ctx)` receive the row, value and formatted value
and return React content. Functions are type-checked, need no template
compiler (string evaluation breaks a strict CSP), and keep untrusted data
out of HTML parsing. For example, `renderCell: ({ row }) => <b>{row.Name}</b>`. See
[Templates](https://salmonui.dev/docs/data-grid/templates) for every template hook.

### Live demo: Column types, ids and reading methods

Live demo: https://salmonui.dev/demos/data-grid/column-api

Columns without `type` infer it from the first non-null value, ids resolve from `id`, then `field`, then a generated id with a warning, the same columns work as an array or as `<DataGridColumn>` children, text that looks like markup stays text, a function template renders rich content, and the column reading methods report ids and visible positions.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Select } from '@salmonui/dropdowns/select';
import { DataGrid, DataGridColumn, type DataGridApi, type DataGridColumn as DataGridColumnDef } from '@salmonui/data-grid';
import type { DataGridWarning } from '@salmonui/data-grid/engine';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(200, 5);

const FORMS = [
  { value: 'array', label: 'columns array' },
  { value: 'children', label: 'DataGridColumn children' },
];

// Plain text that looks like markup: React escapes it, so it shows literally.
const markup = (o: Order) => `<b>${o.customer}</b>`;

// The same columns as an array and as <DataGridColumn> children. No `type` on most columns:
// the type is inferred from the first non-null value. The Status column has neither
// `id` nor `field`, so its id is generated with a development warning.
const columns: DataGridColumnDef<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 140 },
  { field: 'quantity', header: 'Qty', align: 'end', width: 80 },
  { field: 'placed', header: 'Placed', format: 'yMMMd', width: 130 },
  { field: 'shipped', header: 'Shipped', width: 100 },
  { id: 'markup', header: 'Markup as text', valueGetter: markup, width: 170 },
  {
    header: 'Status',
    width: 130,
    // Function template: rich content from a render function, never a `${field}` string.
    renderCell: ({ row }) => (
      <span className="demo-badge" data-tone={row.shipped ? 'success' : 'info'}>
        <strong>{row.shipped ? 'Shipped' : 'Open'}</strong>
      </span>
    ),
  },
];

function ColumnChildren() {
  return [
    <DataGridColumn key="id" field="id" header="Order" primaryKey width={110} />,
    <DataGridColumn key="customer" field="customer" header="Customer" width={140} />,
    <DataGridColumn key="quantity" field="quantity" header="Qty" align="end" width={80} />,
    <DataGridColumn key="placed" field="placed" header="Placed" format="yMMMd" width={130} />,
    <DataGridColumn key="shipped" field="shipped" header="Shipped" width={100} />,
    <DataGridColumn<Order> key="markup" id="markup" header="Markup as text" valueGetter={markup} width={170} />,
    <DataGridColumn<Order>
      key="status"
      header="Status"
      width={130}
      renderCell={({ row }) => (
        <span className="demo-badge" data-tone={row.shipped ? 'success' : 'info'}>
          <strong>{row.shipped ? 'Shipped' : 'Open'}</strong>
        </span>
      )}
    />,
  ];
}

// The readout is a plain table: start-aligned, monospace, with row rules.
const tableStyle = { marginBlockStart: 'var(--salmon-space-3)', borderCollapse: 'collapse', fontFamily: 'var(--salmon-font-mono)', fontSize: 'var(--salmon-font-size-sm)' } as const;
const cellStyle = { textAlign: 'start', padding: 'var(--salmon-space-2) var(--salmon-space-5) var(--salmon-space-2) 0', borderBlockEnd: '1px solid var(--salmon-border-subtle)' } as const;

interface ColumnReadout {
  readonly id: string;
  readonly field: string;
  readonly type: string;
  readonly source: string;
  readonly index: number;
}

export default function ColumnApiDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  // Development warnings are delivered after commit, so they can be written to state.
  const [warnings, setWarnings] = useState<readonly string[]>([]);
  const [form, setForm] = useState<'array' | 'children'>('array');
  const [readout, setReadout] = useState<readonly ColumnReadout[]>([]);
  const [summary, setSummary] = useState('');
  const read = () => {
    const grid = api.current;
    if (!grid) return;
    // getColumns: every leaf; getColumnIndex / getColumnAt: positions in getVisibleColumns().
    setReadout(
      grid.getColumns().map((c) => ({ id: c.columnId, field: c.field ?? '-', type: c.type, source: c.typeSource, index: grid.getColumnIndex(c.columnId) })),
    );
    setSummary(
      `getColumn('customer'): ${grid.getColumn('customer')?.headerText}; getColumnAt(2): ${grid.getColumnAt(2)?.headerText}; ` +
        `visible ${grid.getVisibleColumns().length} of ${grid.getColumns().length}; warnings: ${warnings.join(' | ') || '-'}`,
    );
  };
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Columns as{' '}
          <Select aria-label="Columns as" data={FORMS} value={form} onValueChange={(value) => value != null && setForm(value as 'array' | 'children')} />
        </label>
        <Button variant="outline" onClick={read}>
          Read columns
        </Button>
        <Button variant="outline" onClick={() => api.current?.hideColumns('quantity')}>
          Hide Qty
        </Button>
        <Button variant="outline" onClick={() => api.current?.showColumns('quantity')}>
          Show Qty
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders with inferred column types"
        data={orders}
        // Pass one form: with both, the children win and development builds warn.
        {...(form === 'array' ? { columns } : null)}
        height={320}
        locale="en-US"
        timeZone="UTC"
        ref={api}
        onWarning={(warning: DataGridWarning) => {
          setWarnings((list) => [...list, warning.code]);
        }}
      >
        {form === 'children' ? ColumnChildren() : null}
      </DataGrid>
      <p className="demo-status" data-demo="summary">
        {summary || 'Press Read columns.'}
      </p>
      {readout.length > 0 ? (
        <table className="demo-table" data-demo="columns" style={tableStyle}>
          <thead>
            <tr>
              <th scope="col" style={cellStyle}>id</th>
              <th scope="col" style={cellStyle}>field</th>
              <th scope="col" style={cellStyle}>type</th>
              <th scope="col" style={cellStyle}>typeSource</th>
              <th scope="col" style={cellStyle}>getColumnIndex</th>
            </tr>
          </thead>
          <tbody>
            {readout.map((c) => (
              <tr key={c.id} data-column={c.id}>
                <td style={cellStyle}>{c.id}</td>
                <td style={cellStyle}>{c.field}</td>
                <td style={cellStyle}>{c.type}</td>
                <td style={cellStyle}>{c.source}</td>
                <td style={cellStyle}>{c.index}</td>
              </tr>
            ))}
          </tbody>
        </table>
      ) : null}
    </>
  );
}
```

## Capability flags, locked and identity columns

Data Grid-wide features turn on with `sorting`, `filtering`, `search`,
`grouping`, `editing`, `resizable` and `reorderable`; a column turns its
part off with `sortable`, `filterable`, `searchable`, `groupable`,
`editable`, `resizable` or `reorderable` set to `false`. The flags are enforced
by the core, so methods respect them as well as the header, filter bar,
search box and menus.

`column.lockPosition` keeps a column first in its
pinned zone: it cannot be reordered, and no other column can move before it.
`column.identity` (`isIdentity`) marks a key the server generates;
it defaults `editable` to `false`.

### Live demo: Column capabilities, locked and identity columns

Live demo: https://salmonui.dev/demos/data-grid/column-capabilities

Sorting, filtering, search, grouping, editing, resizing and reordering on for the grid and turned off per column with `sortable`, `filterable`, `searchable`, `groupable`, `editable`, `resizable` and `reorderable`; a `lockPosition` first column and an `identity` key column.

`Demo.tsx`:

```tsx
'use client';

import { DataGrid, type DataGridColumn, type DataGridFiltering } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(400, 3);

// Per-column capability flags refine the grid-wide features turned on below.
const columns: DataGridColumn<Order>[] = [
  // fixed at the start, not reorderable, and nothing can move before it.
  // a server-generated key: `identity` defaults `editable` to false.
  { field: 'id', header: 'Order', primaryKey: true, identity: true, lockPosition: true, width: 110 },
  { field: 'customer', header: 'Customer (not sortable, not searchable)', sortable: false, searchable: false, width: 230 },
  { field: 'country', header: 'Country (not filterable)', filterable: false, width: 190 },
  { field: 'category', header: 'Category (not groupable)', groupable: false, width: 190 },
  { field: 'product', header: 'Product (read-only)', editable: false, width: 170 },
  { field: 'amount', header: 'Amount (fixed size and place)', type: 'number', format: 'C2', align: 'end', resizable: false, reorderable: false, width: 220 },
  { field: 'city', header: 'City', width: 120 },
];

const filtering: DataGridFiltering = { ui: 'row' };

export default function ColumnCapabilitiesDemo() {
  const [log, push] = useEventLog();
  return (
    <>
      <DataGrid<Order>
        aria-label="Orders with per-column capability flags"
        data={orders}
        columns={columns}
        sorting
        filtering={filtering}
        search
        grouping
        columnMenu
        editing
        resizable
        reorderable
        toolbar={['search']}
        // The headers name the capability each column turns off: wrap them instead of truncating.
        textWrap="header"
        height={380}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        onColumnReorder={(event) => push(`reorder (${event.source}): ${event.field} ${event.fromIndex} → ${event.toIndex}`)}
        onEditStart={(event) => push(`edit ${event.rowId}`)}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## Row numbers

A column with `type: 'rowNumber'` and no field numbers the rows.
The number is the position of the data row in the current view: it follows
sorting and filtering, continues across pages (page 2 of 25-row pages starts
at 26) and skips group captions and footers. Only rendered rows compute a
number, so the column adds no work beyond the visible window. The column
defaults to the header `#` (`localeText.rowNumberColumnHeader`), end
alignment, and no sorting, filtering, searching, grouping or editing; its
own fields win, and `renderCell` receives the number as `value`.

### Live demo: Row number column

Live demo: https://salmonui.dev/demos/data-grid/row-number

A `type: 'rowNumber'` column numbering 2,000 orders across pages, sorts and groups, with the header group toggle buttons.

`Demo.tsx`:

```tsx
'use client';

import { DataGrid, type DataGridColumn, type DataGridGrouping, type DataGridPaging } from '@salmonui/data-grid';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(2_000, 21);

const columns: DataGridColumn<Order>[] = [
  // The row number column: no field; numbers follow the visible order across pages and groups.
  { type: 'rowNumber', pinned: 'start' },
  { field: 'id', header: 'Order', primaryKey: true, width: 120, groupable: false },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'category', header: 'Category', width: 120 },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
];

// Constants: options props are reactive.
const paging: DataGridPaging = { pageSize: 25 };
// Header group toggles; chips toggle the group order because sorting is on.
const grouping: DataGridGrouping<Order> = { showHeaderToggle: true };

export default function RowNumberDemo() {
  return (
    <>
      <DataGrid<Order>
        aria-label="Numbered orders"
        data={orders}
        columns={columns}
        sorting
        paging={paging}
        grouping={grouping}
        height={380}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
      />
      <p className="demo-status">Sort, page, or group with the header group buttons: the numbers count data rows in view order, continue across pages and skip group captions.</p>
    </>
  );
}
```

## Visibility, resizing, reordering and auto-size

Columns are hidden and shown through the reactive column `hidden` field or
by id or field through `api.hideColumns()` and `api.showColumns()`,
which raise `onBeforeColumnVisibilityChange` (cancellable) and
`onColumnVisibilityChange`. Resizing and reordering are opt in
with the grid `resizable` and `reorderable` props. Header edges resize
columns with the pointer and the keyboard; double-clicking an edge,
or calling the auto-size method,
fits the width to the header and the rendered cells. Headers drag
to reorder, and `Alt+ArrowLeft` / `Alt+ArrowRight` move the focused
header. Width, order and visibility are engine state, so they never
re-render rows while a drag is in progress.

On a focused header, `Ctrl+Alt+ArrowRight` and `Ctrl+Alt+ArrowLeft` widen and
narrow the column by 10 px (mirrored in RTL), and `Ctrl+Alt+Enter` auto-sizes
it. Every width, from the pointer, the keyboard, auto-size,
`api.setColumnWidth()` or a changed `column.width`, is clamped to the
column's `minWidth` and `maxWidth` by the core.

Pointer resizes raise `onColumnResizeStart`, `onColumnResize` once per frame
and `onColumnResizeEnd` with `{ field, width, previousWidth }`; `preventDefault()` in
`onColumnResizeStart` cancels the gesture. The keyboard resize keys raise the
same three events once per key press with `source: 'keyboard'`, so
a reactive `column.width` stays in sync; `api.autoSizeColumns()` and the
column menu auto-size items do not raise them. Header drags raise `onColumnDragStart`,
`onColumnDrag` per frame and `onColumnDrop` with `{ field, fromIndex,
toIndex }` (`toIndex` is -1 while the drop target is invalid); every
move, by pointer, keyboard or method, also raises `onBeforeColumnReorder`
(cancellable) and `onColumnReorder`. `preventDefault()` in
`onBeforeColumnReorder` keeps the column where it was: a pointer drag still
reports `onColumnDrop`, but the order does not change and `onColumnReorder`
does not fire. While a header is dragged, a preview with the header text
follows the pointer and a line marks the drop position; both disappear on
drop or when the pointer is cancelled (a cancelled pointer moves nothing).

`api.moveColumn(field, toIndex)` moves a column to an index of the visible
columns; it is rejected across pinned zones and
for locked columns. To keep widths, treat `column.width` as
reactive state written back from `onColumnResizeEnd`, as the demo does for
Customer, or let `persistState` save widths with the rest of the grid state
(see [State persistence](https://salmonui.dev/docs/data-grid/state-persistence)).

### Live demo: Visibility, resize, reorder and auto-size

Live demo: https://salmonui.dev/demos/data-grid/column-layout

Toggle columns through the reactive column `hidden` field or the API, drag header edges or press Ctrl+Alt+Arrow to resize within the min and max widths, drag headers or press Alt+Arrow to reorder (both opt in with `resizable` and `reorderable`), move columns with `api.moveColumn`, drive a width reactively, and watch the resize and drag events.

`Demo.tsx`:

```tsx
'use client';

import { useMemo, useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { NumberField } from '@salmonui/inputs/number-field';
import { DataGrid, type DataGridApi, type DataGridColumn } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(300);

const baseColumns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110, reorderable: false },
  { field: 'customer', header: 'Customer', width: 150, minWidth: 100, maxWidth: 280 },
  { field: 'city', header: 'City', width: 120 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'product', header: 'Product', width: 140 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 110 },
  { field: 'note', header: 'Note', width: 120, resizable: false },
];

// A bordered group that matches the Salmon field border and radius instead of the browser default.
const fieldsetStyle = { margin: 0, padding: 'var(--salmon-space-2) var(--salmon-space-3) var(--salmon-space-3)', border: '1px solid var(--salmon-border-default)', borderRadius: 'var(--salmon-radius-md)' } as const;

const toggleable = ['customer', 'city', 'country', 'product', 'amount', 'note'] as const;

export default function ColumnLayoutDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  // Column `hidden` is reactive: the checkboxes drive it, and the grid reports its own changes.
  const [hidden, setHidden] = useState<ReadonlySet<string>>(() => new Set(['note']));
  // Column `width` is reactive too: the input drives the Customer width, and a pointer resize writes it back.
  const [customerWidth, setCustomerWidth] = useState(150);
  const [blockCountry, setBlockCountry] = useState(true);
  const [blockProduct, setBlockProduct] = useState(true);
  const columns = useMemo(
    () => baseColumns.map((c) => ({ ...c, hidden: hidden.has(c.field ?? ''), ...(c.field === 'customer' ? { width: customerWidth } : null) })),
    [hidden, customerWidth],
  );
  // Per-frame events are counted, not logged; the count is read when the gesture ends.
  const frames = useRef(0);
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <fieldset className="demo-toolbar" style={fieldsetStyle}>
          <legend>Visible columns</legend>
          {toggleable.map((field) => (
            <Checkbox
              key={field}
              checked={!hidden.has(field)}
              onCheckedChange={(checked) => {
                const next = new Set(hidden);
                if (checked) next.delete(field);
                else next.add(field);
                setHidden(next);
              }}
            >
              {field}
            </Checkbox>
          ))}
        </fieldset>
        <Button variant="outline" onClick={() => api.current?.autoSizeColumns()}>
          Auto-size all
        </Button>
        <Button variant="outline" onClick={() => api.current?.autoSizeColumns('customer')}>
          Auto-size Customer
        </Button>
        <Button variant="outline" onClick={() => api.current?.hideColumns('city')}>
          Hide City through the API
        </Button>
      </div>
      <div className="demo-toolbar">
        <label>
          Customer width (px, clamped to 100..280){' '}
          <NumberField
            aria-label="Customer width (px, clamped to 100..280)"
            min={60}
            max={400}
            step={10}
            value={customerWidth}
            data-demo="customer-width"
            onValueChange={(next) => {
              if (next !== null && Number.isFinite(next) && next > 0) setCustomerWidth(next);
            }}
          />
        </label>
        <Checkbox checked={blockCountry} onCheckedChange={(checked) => setBlockCountry(checked)}>
          Cancel resizing Country in onColumnResizeStart
        </Checkbox>
        <Checkbox checked={blockProduct} onCheckedChange={(checked) => setBlockProduct(checked)}>
          Cancel moving Product in onBeforeColumnReorder
        </Checkbox>
        <Button variant="outline" onClick={() => push(`moveColumn amount → 1: ${api.current?.moveColumn('amount', 1).status}`)}>
          Move Amount to position 1
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders with resizable, reorderable and hideable columns"
        data={orders}
        columns={columns}
        resizable
        reorderable
        height={360}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        onColumnVisibilityChange={(event) => {
          const next = new Set(hidden);
          for (const field of event.hidden) next.add(field);
          for (const field of event.shown) next.delete(field);
          setHidden(next);
          push(`visibility (${event.source}): hidden ${event.hidden.join(', ') || '-'}; shown ${event.shown.join(', ') || '-'}`);
        }}
        onColumnResizeStart={(event) => {
          frames.current = 0;
          if (blockCountry && event.field === 'country') {
            event.preventDefault();
            push('resize start: country (prevented)');
            return;
          }
          push(`resize start: ${event.field} at ${Math.round(event.width)}`);
        }}
        onColumnResize={() => {
          frames.current += 1;
        }}
        onColumnResizeEnd={(event) => {
          if (event.field === 'customer') setCustomerWidth(Math.round(event.width));
          push(`resize (${event.source}): ${event.field} ${Math.round(event.previousWidth)} → ${Math.round(event.width)} after ${frames.current} frames`);
        }}
        onColumnDragStart={(event) => {
          frames.current = 0;
          push(`drag start: ${event.field} from ${event.fromIndex}`);
        }}
        onColumnDrag={() => {
          frames.current += 1;
        }}
        onColumnDrop={(event) => push(`drop: ${event.field} ${event.fromIndex} → ${event.toIndex} after ${frames.current} frames`)}
        onBeforeColumnReorder={(event) => {
          if (blockProduct && event.field === 'product') {
            event.preventDefault();
            push(`reorder (${event.source}): product ${event.fromIndex} → ${event.toIndex} (prevented)`);
          }
        }}
        onColumnReorder={(event) => push(`reorder (${event.source}): ${event.field} ${event.fromIndex} → ${event.toIndex}`)}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## Column fit and computed headers

`resizeMode` picks how the
columns relate to the grid width. `'normal'`, the default, keeps every
width: narrow columns leave empty space at the end and wide ones scroll, and
a resize changes only the resized column. With `'auto'`, columns narrower
than the grid stretch in proportion to their width until they fill it,
again whenever the grid is resized; `maxWidth` caps a column and columns
with `resizable: false` (such as the selection column) keep their width.
Dragging a header edge then re-fits the other columns live, and the release
stores the fitted widths so nothing jumps. Columns are never shrunk below
their widths to avoid scrolling: wide
content still scrolls horizontally (shrinking below declared widths would truncate content and add a layout
pass on every viewport resize). To fit more columns without scrolling, use
`resizeMode="auto"` and give columns a smaller `width` or a percentage
where they must fit without scrolling.

```tsx
<DataGrid data={orders} columns={columns} resizable resizeMode="auto" />
```

`headerValueGetter` computes a
header text from the compiled column, for example to add a unit or a
currency. It runs when the column compiles, and its result is the header
text everywhere: the header cell, the column chooser and menu, filter and
group labels, accessible names, and CSV, Excel and PDF exports. Give it new
values by passing a new column definition.

```tsx
{ field: 'amount', type: 'number', headerValueGetter: () => `Amount (${currency})` }
```

### Live demo: Column fit and computed headers

Live demo: https://salmonui.dev/demos/data-grid/column-fit

Switch `resizeMode` between `'auto'` (columns stretch to fill the grid and a resize re-fits the others) and `'normal'` (widths are kept and the space stays empty), and compute header text with `headerValueGetter`.

`Demo.tsx`:

```tsx
'use client';

import { useMemo, useState } from 'react';
import { Select } from '@salmonui/dropdowns/select';
import { DataGrid, type DataGridColumn } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(200);
const modeItems = [
  { value: 'auto', label: 'auto' },
  { value: 'normal', label: 'normal' },
];
const currencyItems = [
  { value: 'USD', label: 'USD' },
  { value: 'EUR', label: 'EUR' },
];

export default function ColumnFitDemo() {
  const [mode, setMode] = useState<'normal' | 'auto'>('auto');
  const [currency, setCurrency] = useState<'USD' | 'EUR'>('USD');
  const [log, push] = useEventLog();
  // headerValueGetter computes the header text from the compiled column.
  // The definitions change with the currency, so the columns recompile and the headers follow.
  const columns = useMemo<DataGridColumn<Order>[]>(
    () => [
      { field: 'id', header: 'Order', primaryKey: true, width: 110 },
      { field: 'customer', header: 'Customer', width: 150, minWidth: 100 },
      { field: 'country', header: 'Country', width: 110, maxWidth: 160 },
      { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 130, headerValueGetter: (c) => `${c.headerText} (${c.type})` },
      { field: 'unitPrice', type: 'number', format: 'C2', align: 'end', width: 150, headerValueGetter: () => `Unit price (${currency})` },
      { field: 'amount', type: 'number', format: 'C2', align: 'end', width: 140, headerValueGetter: () => `Amount (${currency})` },
    ],
    [currency],
  );
  return (
    <>
      <div className="demo-toolbar">
        <label>
          resizeMode{' '}
          <Select aria-label="resizeMode" data-demo="resize-mode" data={modeItems} value={mode} onValueChange={(value) => value != null && setMode(value as 'normal' | 'auto')} />
        </label>
        <label>
          Currency{' '}
          <Select aria-label="Currency" data-demo="currency" data={currencyItems} value={currency} onValueChange={(value) => value != null && setCurrency(value as 'USD' | 'EUR')} />
        </label>
      </div>
      <DataGrid<Order>
        aria-label="Orders with fitted columns and computed headers"
        data={orders}
        columns={columns}
        resizable
        resizeMode={mode}
        columnChooser
        height={320}
        locale="en-US"
        currency={currency}
        timeZone="UTC"
        onColumnResizeEnd={(event) => push(`resize (${mode}): ${event.field} ${Math.round(event.previousWidth)} → ${Math.round(event.width)}`)}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## API reference

[`DataGridColumn`](https://salmonui.dev/docs/reference/data-grid/DataGridColumn) and the
core [`ColumnDef`](https://salmonui.dev/docs/reference/data-grid/engine/ColumnDef) list every column
field; the column methods are on
[`DataGridApi`](https://salmonui.dev/docs/reference/data-grid/DataGridApi).
