# Detail rows

> Expandable detail rows with a render prop, async loading, per-row and expand-all control, keyboard support and virtualization.

Canonical: https://salmonui.dev/docs/data-grid/detail-rows

`renderDetail` renders a detail row below every expanded row. The grid adds a toggle column in front of the columns; the detail
row is one `role="row"` with a single cell spanning every column, so it
spans the full width even with pinned columns. With pinned rows
(row pinning), detail rows belong to the scrolling rows only: a
pinned row shows no toggle and no detail row, and Enter on its toggle cell
does nothing. `api.expandDetail()` still records the expansion of a pinned
row, and its detail row appears once the row is unpinned. Detail rows of
scrolling rows render directly below their row, under the pinned zone, and
scroll with it. The toggle button
carries `aria-expanded` (a row of a `grid` may not), and the parent row
`data-expanded` for styles and row templates. `detailHeight` is the estimated height before the
row is measured (default 150 px).

```tsx
<DataGrid
  aria-label="Orders"
  data={orders}
  columns={columns}
  renderDetail={({ row, collapse }) => <OrderSummary order={row} onClose={collapse} />}
/>
```

## Loading and rows without a detail

`loadDetail({ rowId, row, signal })` loads the content of a row when it is
expanded. `renderDetail`
receives `status` (`loading`, `ready`, `error`), `data`, `error` and
`retry`; the load runs once per row object and is aborted when the row is
replaced. `hasDetail(row)` hides the toggle for rows without a detail.

## Expanding

Methods expand or collapse one detail row or all of them:
`expandDetail(rowId)`, `collapseDetail(rowId)`, `toggleDetail(rowId)`,
`expandAllDetails()`, `collapseAllDetails()`, `isDetailExpanded(rowId)`.
`defaultExpandedDetails` starts with every row (`true`) or a list of row
ids expanded. `onBeforeDetailToggle` (cancel with `preventDefault()`) and
`onDetailToggle` fire for each row. Expansion is kept by row id across
sorting, filtering, paging and data updates.

## Keyboard

Enter or Space on the toggle cell toggles the detail. Arrow keys
move onto the detail row; Enter moves focus into its content and Escape
returns. Mod+ArrowDown and Mod+ArrowUp (Mod is Ctrl, or ⌘ on macOS) expand
and collapse every detail row when the grid is not grouped.

## Virtualization and export

Detail rows are rows of the virtualized row model: only rendered detail
rows mount, and their measured heights feed sparse row metrics, so a grid
of 10,000 expanded rows scrolls like a plain one. Excel and PDF
exports follow the expansion (`hierarchy: 'expanded' | 'all' | 'none'`): the
`detail` export hook returns `{ text }` lines for a detail template, and
child grids are written automatically (see
[Child grids](https://salmonui.dev/docs/data-grid/child-grids)). `print()` and `printing` take the same
`detail` hook, so a detail template prints as its `{ text }` lines. In
`'expanded'` mode (the default) only rows whose detail is expanded get a
block, whatever the hook returns for the others; `'all'` calls the hook for
every row and `'none'` writes no detail rows. CSV has no detail rows.

### Live demo: Detail rows

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

A detail row under each expanded order of 10,000 virtualized rows, with an async loader, rows without a detail, expand-all and toggle events.

`Demo.tsx`:

```tsx
'use client';

import { useRef } from 'react';
import { Button } from '@salmonui/buttons/button';
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(10_000, 7);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110, pinned: 'start' },
  { field: 'customer', header: 'Customer', width: 160 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  { field: 'placed', header: 'Placed', type: 'datetime', format: 'yMMMd', width: 130 },
];

const wait = (ms: number, signal: AbortSignal) =>
  new Promise<void>((resolve, reject) => {
    const t = setTimeout(resolve, ms);
    signal.addEventListener('abort', () => {
      clearTimeout(t);
      reject(new Error('aborted'));
    });
  });

export default function DetailRowsDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" type="button" onClick={() => api.current?.expandAllDetails()}>
          Expand all
        </Button>
        <Button variant="outline" type="button" onClick={() => api.current?.collapseAllDetails()}>
          Collapse all
        </Button>
        <Button variant="outline" type="button" onClick={() => api.current?.toggleDetail(orders[2]?.id ?? '')}>
          Toggle the third order
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders with details"
        data={orders}
        columns={columns}
        height={460}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        detailHeight={96}
        hasDetail={(row) => row.priority !== 'Low'}
        loadDetail={async ({ row, signal }) => {
          await wait(300, signal);
          const line = `${row.quantity} × ${row.product} at $${row.unitPrice.toFixed(2)}`;
          return row.note ? `${line} — ${row.note}` : line;
        }}
        renderDetail={({ row, status, data, retry, collapse }) => (
          <div className="demo-detail">
            <strong>{row.customer}</strong>, {row.city} ({row.priority} priority)
            <p>{status === 'ready' ? String(data) : status === 'error' ? <Button variant="outline" type="button" onClick={retry}>Retry</Button> : 'Loading…'}</p>
            <Button variant="outline" type="button" onClick={collapse}>
              Close
            </Button>
          </div>
        )}
        onBeforeDetailToggle={(event) => push(`before ${event.expanded ? 'expand' : 'collapse'} ${event.rowId} (${event.source})`)}
        onDetailToggle={(event) => push(`${event.expanded ? 'expanded' : 'collapsed'} ${event.rowId}`)}
      />
      <p className="demo-status">
        Low-priority orders have no detail. Keyboard: Enter or Space on the toggle cell, Enter on a detail row moves into it, Escape returns,
        Ctrl+Down / Ctrl+Up expand or collapse all.
      </p>
      <EventLog entries={log} />
    </>
  );
}
```

## API reference

[`DataGridDetailContext`](https://salmonui.dev/docs/reference/data-grid/DataGridDetailContext),
[`DataGridDetailLoadContext`](https://salmonui.dev/docs/reference/data-grid/DataGridDetailLoadContext)
and [`DataGridDetailToggleEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridDetailToggleEvent)
describe the render, load and toggle payloads;
[`DataGridProps`](https://salmonui.dev/docs/reference/data-grid/DataGridProps) lists the
detail props and [`DataGridApi`](https://salmonui.dev/docs/reference/data-grid/DataGridApi)
the expand methods.
