# Selection

> Row, cell and column selection with pointer, keyboard and methods; id-based, persistent and virtualization-safe.

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

Selection is on by default as single row selection; `selection={false}`
turns it off, and an object configures it. It is stored by row id
and column id, never by view index, so virtualization and live data changes
never shift it to another row.

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

<DataGrid
  aria-label="Orders"
  data={orders}
  columns={[{ field: 'select', type: 'selection' }, ...columns]}
  selection={{ multiple: true, persistent: true, rowIds: selectedIds }}
  onSelectionChange={(event) => setSelectedIds(event.rowIds)}
/>
```

## Rows

`multiple` (default `false`) switches from single to multiple selection.
Ctrl/⌘+click toggles a row and Shift+click selects a range.
A checkbox column (a column with `type: 'selection'`) adds a
header select-all checkbox; `checkboxOnly` makes it the only way to
select, and `checkboxRowClick: 'replace'` makes a plain row click
replace the checkbox selection instead of toggling the row (`'add'`, the
default). With `toggle` (default `true`) clicking the only selected
row deselects it, and `additive` toggles rows without a modifier.

By default a sort, filter, search, grouping or page change clears the
selection. `persistent: true` keeps it across those changes (this
also works for cells and does not need multiple selection).

Initial and controlled selection use row ids: `selection.rowIds` is
reactive, so a changed array re-applies. There is no selection by
row index, on purpose: an index is invalidated by every sort, filter, page
or live update, while an id is not. To select by position, map the index
to the id of that row (`api.getViewRows()[index]` through
`getRowId` or the `primaryKey` column) and pass it in `rowIds`.

`api.selectAll()` selects every filtered row in O(1): it stores a scope plus
excluded ids, which serializes and survives paging;
`selectAll({ scope: 'page' })` selects the current page only.

Methods select rows or id ranges (`selectRows(rowIds, { mode })`,
`selectRowRange(fromRowId, toRowId)`), clear rows, cells or columns
(`clearSelection({ rows, cells, columns })`), and read the
selection (`getSelectedRows()`, `getSelectedRowIds()`, `isRowSelected()`,
and the serializable `getSelection()` / `setSelection()`). The
cancelable `onBeforeSelectionChange` and `onSelectionChange` report the
selected `rowIds`, the `added` and `removed` ids, `rows()`, the input
`target` and the `scope`. Rows and cells expose `aria-selected`.

### Live demo: Row selection

Live demo: https://salmonui.dev/demos/data-grid/selection-rows

Single and multiple row selection, the `type: 'selection'` checkbox column with select-all, checkbox-only and replace-on-row-click modes, toggle, additive clicks, persistence across filtering, cancelable changes and the selection methods.

`Demo.tsx`:

```tsx
'use client';

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

const orders = createOrders(2_000, 5);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 160 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  { field: 'shipped', header: 'Shipped', type: 'boolean', displayAsCheckbox: true, align: 'center', width: 100 },
];

interface Settings {
  multiple: boolean;
  // Adds the `type: 'selection'` checkbox column.
  checkboxColumn: boolean;
  checkboxOnly: boolean;
  replaceOnRowClick: boolean;
  toggle: boolean;
  additive: boolean;
  persistent: boolean;
}

const initial: Settings = { multiple: true, checkboxColumn: true, checkboxOnly: false, replaceOnRowClick: false, toggle: true, additive: false, persistent: true };

const selectionColumn: DataGridColumn<Order> = { type: 'selection' };
const withCheckbox = [selectionColumn, ...columns];
const MULTIPLE = [
  { value: 'single', label: 'single' },
  { value: 'multiple', label: 'multiple' },
];

function toSelection(s: Settings, rowIds: readonly string[]): DataGridSelection {
  return {
    multiple: s.multiple,
    mode: 'row',
    checkboxOnly: s.checkboxOnly,
    checkboxRowClick: s.replaceOnRowClick ? 'replace' : 'add',
    toggle: s.toggle,
    additive: s.additive,
    persistent: s.persistent,
    rowIds,
  };
}

export default function SelectionRowsDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [settings, setSettings] = useState<Settings>(initial);
  const [selected, setSelected] = useState<readonly string[]>(['ORD-10001', 'ORD-10003']);
  const [lockFirst, setLockFirst] = useState(false);
  const [log, push] = useEventLog();
  const flag = (key: keyof Settings) => (
    <Checkbox checked={Boolean(settings[key])} onCheckedChange={(checked) => setSettings({ ...settings, [key]: checked })}>
      {key}
    </Checkbox>
  );
  return (
    <>
      <div className="demo-toolbar">
        <label>
          multiple
          <Select aria-label="multiple" data={MULTIPLE} value={settings.multiple ? 'multiple' : 'single'} onValueChange={(value) => value != null && setSettings({ ...settings, multiple: value === 'multiple' })} />
        </label>
        {flag('checkboxColumn')}
        {flag('checkboxOnly')}
        {flag('replaceOnRowClick')}
        {flag('toggle')}
        {flag('additive')}
        {flag('persistent')}
        <Checkbox checked={lockFirst} onCheckedChange={(checked) => setLockFirst(checked)}>
          Cancel changes that touch ORD-10000
        </Checkbox>
      </div>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.selectRows(['ORD-10005', 'ORD-10006'])}>
          Select 10005, 10006
        </Button>
        <Button variant="outline" onClick={() => api.current?.selectRowRange('ORD-10010', 'ORD-10020', { mode: 'add' })}>
          Add range 10010–10020
        </Button>
        <Button variant="outline" onClick={() => api.current?.selectAll({ scope: 'filtered' })}>
          Select all (filtered)
        </Button>
        <Button variant="outline" onClick={() => api.current?.filterColumn('country', 'equal', 'Japan')}>
          Filter: Japan
        </Button>
        <Button variant="outline" onClick={() => api.current?.clearFiltering()}>
          Clear filter
        </Button>
        <Button variant="outline" onClick={() => api.current?.clearSelection()}>
          Clear selection
        </Button>
        <Button variant="outline" onClick={() => push(`getSelectedRows(): ${api.current?.getSelectedRows().length ?? 0} rows; scope ${api.current?.getSelection()?.scope ?? '-'}`)}>
          Read selection
        </Button>
      </div>
      <DataGrid<Order>
        key={JSON.stringify(settings)}
        aria-label="Orders with row selection"
        data={orders}
        columns={settings.checkboxColumn ? withCheckbox : columns}
        sorting
        filtering
        height={360}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        selection={toSelection(settings, selected)}
        onBeforeSelectionChange={(event) => {
          if (lockFirst && (event.added.includes('ORD-10000') || event.removed.includes('ORD-10000'))) {
            push('cancelled: ORD-10000 is locked');
            event.preventDefault();
          }
        }}
        onSelectionChange={(event) => {
          setSelected(event.rowIds);
          push(`${event.source}: +${event.added.length} −${event.removed.length} → ${event.scope === 'allFiltered' ? `all filtered except ${event.excludedRowIds.length}` : `${event.rowIds.length} selected`}`);
        }}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## Cells and columns

`mode: 'cell'`, or row plus cell mode `mode: 'both'`, selects
`cellRange: 'flow'` (text-like, the default) or `'box'` / `'boxWithBorder'`
(rectangular) ranges; `columns: true` adds column selection.
`selectCells(cells, { mode })`, `selectCellRange(anchor, focus)`
and `selectColumns(fields, { mode })` select from code, and
`getSelectedCells()` / `getSelectedColumns()` read the result.

The keyboard map (Mod is Ctrl, or ⌘ on macOS):

| Keys | Action |
| --- | --- |
| Arrow keys | Move focus |
| Shift+Arrow keys | Extend the selection |
| Enter / Shift+Enter | Move to the cell below / above and select it |
| Space | Toggle the focused row or cell |
| Shift+Space | Select the focused row |
| Ctrl+Space | Toggle the focused column (with `columns: true`) |
| Mod+A | Select every row in view, or every cell in cell mode (multiple selection) |
| Mod+Shift+A | Select every filtered row (multiple selection) |
| Escape | Clear the selection |
 Cell and column changes raise the same cancelable
`onBeforeSelectionChange` and `onSelectionChange` events as rows:
`target` is `'cell'` or `'column'`, and `addedCells` / `removedCells` /
`addedColumns` / `removedColumns` list what changed. In row plus cell mode a
click raises a row event and a cell event. Ranges are stored as anchors, so a range can span rows and
columns that are not rendered, so cell selection works with
virtualization.

### Live demo: Cell and column selection

Live demo: https://salmonui.dev/demos/data-grid/selection-cells

Cell and row-plus-cell modes, flow and box cell ranges, column selection, keyboard selection and range selection across virtualized rows and columns.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createWideRows, type WideRow } from '../../lib/fixtures';
import { createWideColumns } from '../../lib/wide';

// Cell selection over 50,000 virtualized rows and 40 virtualized columns.
const rows = createWideRows(50_000);
const columns: DataGridColumn<WideRow>[] = createWideColumns(40);

type Mode = 'cell' | 'both';
type CellMode = 'flow' | 'box' | 'boxWithBorder';
const MODES = [
  { value: 'cell', label: 'cell' },
  { value: 'both', label: 'both' },
];
const CELL_MODES = [
  { value: 'flow', label: 'flow' },
  { value: 'box', label: 'box' },
  { value: 'boxWithBorder', label: 'boxWithBorder' },
];

export default function SelectionCellsDemo() {
  const api = useRef<DataGridApi<WideRow> | null>(null);
  const [mode, setMode] = useState<Mode>('cell');
  const [cellMode, setCellMode] = useState<CellMode>('box');
  const [columnSelection, setColumnSelection] = useState(true);
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <label>
          mode
          <Select aria-label="mode" data={MODES} value={mode} onValueChange={(value) => value != null && setMode(value as Mode)} />
        </label>
        <label>
          cell range
          <Select aria-label="cell range" data={CELL_MODES} value={cellMode} onValueChange={(value) => value != null && setCellMode(value as CellMode)} />
        </label>
        <Checkbox checked={columnSelection} onCheckedChange={(checked) => setColumnSelection(checked)}>
          Column selection
        </Checkbox>
        <Button variant="outline" onClick={() => api.current?.selectCellRange({ rowId: '10', field: 'n1' }, { rowId: '40000', field: 'n5' })}>
          Select rows 10–40,000 × columns 1–5
        </Button>
        <Button variant="outline" onClick={() => api.current?.selectCells([{ rowId: '3', field: 'n2' }], { mode: 'add' })}>
          Add cell (3, Value 2)
        </Button>
        <Button variant="outline" onClick={() => api.current?.selectColumns('s3', { mode: 'toggle' })}>
          Toggle column Text 3
        </Button>
        <Button variant="outline" onClick={() => api.current?.clearSelection({ cells: true, columns: true })}>
          Clear cells and columns
        </Button>
        <Button variant="outline" onClick={() => push(`summary: ${JSON.stringify(api.current?.getSelectionSummary() ?? null)}`)}>
          Read summary
        </Button>
      </div>
      <DataGrid<WideRow>
        key={`${mode}-${cellMode}-${columnSelection}`}
        aria-label="Cell selection over a virtualized grid"
        data={rows}
        columns={columns}
        height={360}
        locale="en-US"
        ref={api}
        selection={{ multiple: true, mode, cellRange: cellMode, columns: columnSelection }}
      />
      <p className="demo-status">
        Click a cell, then Shift+click or Shift+Arrow to extend; Ctrl/⌘+click adds cells; Ctrl/⌘+A selects all; Escape clears.
      </p>
      <EventLog entries={log} />
    </>
  );
}
```

## Range fill

With `editing.fillHandle` and cell
selection, the cell at the bottom-right of the selected range shows a small
square, the fill handle. Dragging it down, up, left or right extends the
range along that one axis (a diagonal drag follows the axis the pointer has
moved farther along) and, on release, fills the new cells by tiling the
source range: a two-row source repeats every two rows. A dashed outline
previews the extended range, the grid auto-scrolls while the pointer is held
at or past the body edge, and Escape cancels the drag. The drag never
touches React state: the preview and the auto-scroll are DOM writes, and the
grid renders once, when the fill is applied. `api.fillSelection(rowId,
field)` is the programmatic form of the same action, and `onBeforeFill`
(`range`, `target`) cancels either with
`preventDefault()`.
Filled cells go through the edit pipeline, so parsing, validation, saving
and undo apply as for typed edits, and pending drafts of the source range
are copied as shown.

```tsx
<DataGrid
  selection={{ mode: 'cell', multiple: true, cellRange: 'box' }}
  editing={{ mode: 'cell', fillHandle: true, undo: true }}
/>;
api.selectCellRange({ rowId: 'ORD-10000', field: 'customer' }, { rowId: 'ORD-10001', field: 'product' });
api.fillSelection('ORD-13999', 'product');
```

The fill addresses cells by row id and walks the full row model, not the
rendered window, so it works with row virtualization and fills rows that are
not rendered, including rows the drag scrolled past. Hold the pointer below or above the body while
dragging and the grid auto-scrolls; the rows that scroll into view join the
fill, and so do the rows that scroll out again. The drag also crosses pin
edges, from a start-pinned column into the scrolling columns or from them
into an end-pinned column. Read-only cells and the key column are skipped.

### Live demo: Range fill

Live demo: https://salmonui.dev/demos/data-grid/fill-range

Drag the fill handle (or call `api.fillSelection()`) to tile the selected cell range over 5,000 virtualized rows, including rows far outside the rendered window, with undo.

`Demo.tsx`:

```tsx
'use client';

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

const orders = createOrders(5_000, 29);

// Order and Customer are pinned to the start and Note to the end: the fill
// handle drags across the pin edges like any other column edge.
const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110, editable: false, pinned: 'start' },
  { field: 'customer', header: 'Customer', width: 150, pinned: 'start' },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80 },
  { field: 'note', header: 'Note', width: 220, pinned: 'end' },
];

// Cell editing commits each filled cell at once; the clipboard module (fill) loads with `fillHandle`.
const editing = { mode: 'cell', fillHandle: true, undo: true } as const;
const selection = { mode: 'cell', multiple: true, cellRange: 'box' } as const;

export default function FillRangeDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [status, setStatus] = useState('Select a cell or a range, then drag its fill handle or use the buttons.');
  // The target cell: the fill extends the selected range down to it.
  const fill = (rowId: string, field: string) => {
    const result = api.current?.fillSelection(rowId, field);
    if (result) setStatus(`fillSelection(${rowId}, ${field}): ${result.status}`);
  };
  return (
    <>
      <div className="demo-toolbar">
        <Button
          variant="outline"
          onClick={() => {
            api.current?.selectCellRange({ rowId: 'ORD-10000', field: 'customer' }, { rowId: 'ORD-10001', field: 'product' });
            setStatus('Selected Customer and Product of the first two orders.');
          }}
        >
          Select the first two rows
        </Button>
        <Button variant="outline" onClick={() => fill('ORD-10005', 'product')}>
          Fill down to row 6
        </Button>
        <Button variant="outline" onClick={() => fill('ORD-13999', 'product')}>
          Fill down to row 4,000
        </Button>
        <Button variant="outline" onClick={() => api.current?.scrollToRow('ORD-13999', { align: 'center' })}>
          Scroll to row 4,000
        </Button>
        <Button variant="outline" onClick={() => setStatus(`undo: ${api.current?.undo().status ?? 'n/a'}`)}>
          Undo
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders with range fill"
        ref={api}
        data={orders}
        columns={columns}
        selection={selection}
        editing={editing}
        onBeforeFill={(e) => setStatus(`onBeforeFill: ${e.range.anchor.rowId}..${e.range.focus.rowId} extended to ${e.target.rowId} / ${e.target.field} (${e.source})`)}
        height={360}
        locale="en-US"
        timeZone="UTC"
      />
      <p className="demo-status" aria-live="polite">
        {status}
      </p>
    </>
  );
}
```

## API reference

[`DataGridSelection`](https://salmonui.dev/docs/reference/data-grid/DataGridSelection)
lists the `selection` options,
[`DataGridSelectionChangeEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridSelectionChangeEvent)
and [`DataGridBeforeFillEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridBeforeFillEvent)
the event payloads, and [`DataGridApi`](https://salmonui.dev/docs/reference/data-grid/DataGridApi)
the selection methods.
