# Events

> The event model - onReady, before-event and after-event pairs, header attributes, and the interaction events of selection, resizing, column drag and the menus.

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

Every grid event is an `on*` prop. Actions come in pairs: `onBefore<Action>`
runs first and cancels the action with `event.preventDefault()`, then
`on<Action>` reports the committed change. Each event object carries `type`,
`source` (`'pointer'`, `'keyboard'`, `'touch'` or `'api'`) and
`defaultPrevented`. An event object is allocated only when its handler is
bound, and scrolling never raises events.

Event objects are plain snapshots, never the grid's internal store objects;
in development builds they are frozen, the `onKeyDown` context
included; production builds skip the freeze. Read them, but do not assign
to their properties. The one exception is the `items` array of a
menu before-event: change it in place (`items.splice(...)`,
`items.push(...)`); reassigning `event.items` throws in development.

## Lifecycle

`onReady(api)` fires once after the first commit of each mount, with the
grid instance; it is the place for startup calls
into the API. When the grid uses a feature that loads on demand (for
example `editing`), `onReady` waits for it. When the grid unmounts, the data source is
disconnected and the in-flight read is aborted.

## Before and after events

There are no generic `actionBegin` / `actionComplete` / `actionFailure`
events. Each action has its own pair with a typed payload:
`onBeforeSortChange` / `onSortChange` (`{ sortBy, previousSortBy, field }`),
`onBeforeFilterChange` / `onFilterChange`, `onBeforeSearchChange` /
`onSearchChange`, `onBeforePageChange` / `onPageChange`,
`onBeforeGroupChange` / `onGroupChange`, and so on. Failures arrive in
`onError` (`{ error, action }`); a failed data load reports
`action: 'data'`. In the demo, the checkbox cancels every sort in
`onBeforeSortChange`, so `onSortChange` never follows.

Typed pairs keep each payload specific instead of a request-type switch
over one shared argument, and an event object is allocated only for a
bound handler. Cancel an action with `event.preventDefault()` in its
`onBefore...` handler, and handle failures in `onError`, whose `action` is
`'data'`, `'save'`, `'persistState'` or the rejected command's feature:

```tsx
<DataGrid
  data={orders}
  columns={columns}
  sorting
  onBeforeSortChange={(event) => {
    if (event.field === 'CustomerName') event.preventDefault();
  }}
  onError={(event) => console.error(event.action, event.error)}
/>
```

## Header attributes

The column's `headerProps` put a class, a style, a `title` and `data-*`
attributes on the header cell. The
Amount header in the demo carries a tooltip and a `data-unit` attribute.
Per-row and per-cell attributes are `getRowProps` and `getCellProps`
([templates](https://salmonui.dev/docs/data-grid/templates)).

## Interaction events

Each feature documents its own events: selection
(`onBeforeSelectionChange` / `onSelectionChange` with `added`, `removed` and
`rowIds`), editing ([editing](https://salmonui.dev/docs/data-grid/editing)), export and print
([export](https://salmonui.dev/docs/data-grid/export)). Column resizing fires `onColumnResizeStart`
(cancellable), `onColumnResize` per frame and `onColumnResizeEnd`; column
drag fires `onColumnDragStart`, `onColumnDrag` and `onColumnDrop`, then the
reorder pair `onBeforeColumnReorder` / `onColumnReorder`; row drag fires
`onRowDragStart`, `onRowDrag`, `onBeforeRowDrop` and `onRowDrop`
([row drag and drop](https://salmonui.dev/docs/data-grid/row-drag)). Per-frame events fire at
most once per animation frame and never touch React state inside the grid.

The menus open through before-events that can cancel them or change their
`items`: `onBeforeColumnMenuOpen` / `onColumnMenuItemClick` for the column
menu and `onBeforeContextMenuOpen` / `onContextMenuItemClick` for the
context menu, whose `target` tells a header, a cell, a row, a group
caption or the pager apart.

### Live demo: Data Grid events

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

onReady on every mount, a cancellable before-event pair, headerProps, and selection, resize, column drag, column menu and context menu events in one on-page log.

`Demo.tsx`:

```tsx
'use client';

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

const orders = createOrders(1_000, 61);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  // headerProps: attributes and classes on the header cell.
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120, headerProps: { title: 'Order total in US dollars', 'data-unit': 'usd' } },
];

// A custom item, so the context menu has an action that applies to every row.
const contextMenu: readonly (DataGridContextMenuItemId | DataGridMenuItem)[] = [{ id: 'logRow', label: 'Log this row' }, 'copy'];

export default function DataGridEventsDemo() {
  const [log, push] = useEventLog(40);
  const [mounted, setMounted] = useState(true);
  const [cancelSort, setCancelSort] = useState(false);
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => setMounted((m) => !m)}>
          {mounted ? 'Unmount the grid' : 'Mount the grid'}
        </Button>
        <Checkbox checked={cancelSort} onCheckedChange={(checked) => setCancelSort(checked)}>
          Cancel sorting in onBeforeSortChange
        </Checkbox>
      </div>
      {mounted ? (
        <DataGrid<Order>
          aria-label="Orders with every interaction logged"
          data={orders}
          columns={columns}
          sorting
          resizable
          reorderable
          columnMenu
          contextMenu={contextMenu}
          selection={{ multiple: true }}
          height={300}
          locale="en-US"
          currency="USD"
          timeZone="UTC"
          onReady={(api) => push(`onReady: ${api.getViewRows().length} view rows`)}
          onBeforeSortChange={(e) => {
            if (cancelSort) e.preventDefault();
            push(`onBeforeSortChange: ${e.field ?? '-'}${cancelSort ? ' (prevented)' : ''}`);
          }}
          onSortChange={(e) => push(`onSortChange: ${e.sortBy.map((s) => `${s.field} ${s.direction}`).join(', ') || 'none'}`)}
          onSelectionChange={(e) => push(`onSelectionChange: +${e.added.length} −${e.removed.length} (${e.source})`)}
          onColumnResizeStart={(e) => push(`onColumnResizeStart: ${e.field}`)}
          onColumnResizeEnd={(e) => push(`onColumnResizeEnd: ${e.field} ${Math.round(e.previousWidth)} → ${Math.round(e.width)}`)}
          onColumnDragStart={(e) => push(`onColumnDragStart: ${e.field}`)}
          onColumnDrop={(e) => push(`onColumnDrop: ${e.field} ${e.fromIndex} → ${e.toIndex}`)}
          onColumnReorder={(e) => push(`onColumnReorder: ${e.field}`)}
          onBeforeColumnMenuOpen={(e) => push(`onBeforeColumnMenuOpen: ${e.field}, ${e.items.length} items`)}
          onColumnMenuItemClick={(e) => push(`onColumnMenuItemClick: ${e.item.id}`)}
          onBeforeContextMenuOpen={(e) => push(`onBeforeContextMenuOpen: ${e.target.kind}${'rowId' in e.target ? ` ${e.target.rowId}` : ''}`)}
          onContextMenuItemClick={(e) => push(`onContextMenuItemClick: ${e.item.id} on ${e.rowIds.join(', ') || '-'}`)}
        />
      ) : (
        <p className="demo-status">The grid is unmounted: its data source, listeners and timers are gone. Mount it again to see onReady.</p>
      )}
      <EventLog entries={log} />
    </>
  );
}
```

## Row and cell clicks

`onRowClick` and `onRowDoubleClick` receive the `rowId`, the `row`, its visible
`rowIndex`, the clicked `field` and `column` (null outside a cell), the row
`element` and the `nativeEvent`. `onCellClick` and `onCellDoubleClick` add
the cell `value` and pass the cell element; the cell event fires before
the row event. They fire for data rows only, not for group
captions, aggregate footers or detail rows. `preventDefault()` on a click
skips the built-in selection and focus; on a double click it skips the edit
start. The grid attaches one delegated listener per event type on the body,
and only while one of these handlers is bound. There is no context-menu
twin: right clicks go through `onBeforeContextMenuOpen`.

### Live demo: Row and cell click events

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

onCellClick, onRowClick, onCellDoubleClick and onRowDoubleClick with the row, the column and the cell value; preventDefault() skips the built-in selection or edit start.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridColumn, type DataGridEditing } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(1_000, 67);

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

// Inline row editing, so a double click has a built-in action (the edit start) to cancel.
const editing: DataGridEditing<Order> = { mode: 'row', add: false, delete: false };

export default function RowEventsDemo() {
  const [log, push] = useEventLog(40);
  const [prevent, setPrevent] = useState(false);
  const mark = prevent ? ' (prevented)' : '';
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={prevent} onCheckedChange={(checked) => setPrevent(checked)}>
          Call preventDefault() in onRowClick and onRowDoubleClick
        </Checkbox>
      </div>
      <DataGrid<Order>
        aria-label="Orders with row and cell click events"
        data={orders}
        columns={columns}
        selection
        editing={editing}
        height={300}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        // The cell event fires first, then the row event; both only for data rows.
        onCellClick={(e) => push(`onCellClick: ${e.rowId} ${e.field} = ${String(e.value)}`)}
        onRowClick={(e) => {
          if (prevent) e.preventDefault();
          push(`onRowClick: ${e.rowId} row ${e.rowIndex} (${e.field ?? '-'})${mark}`);
        }}
        onCellDoubleClick={(e) => push(`onCellDoubleClick: ${e.rowId} ${e.field}`)}
        onRowDoubleClick={(e) => {
          if (prevent) e.preventDefault();
          push(`onRowDoubleClick: ${e.rowId} (${e.column?.header ?? '-'})${mark}`);
        }}
        // The built-in actions the click events can cancel.
        onSelectionChange={(e) => push(`onSelectionChange: +${e.added.length} −${e.removed.length}`)}
        onEditStart={(e) => push(`onEditStart: ${e.rowId}`)}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## API reference

Every event prop is listed on
[`DataGridProps`](https://salmonui.dev/docs/reference/data-grid/DataGridProps), with its
payload type (for example
[`DataGridSortChangeEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridSortChangeEvent),
[`DataGridRowClickEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridRowClickEvent)
and [`DataGridErrorEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridErrorEvent)).
