# Child grids

> Hierarchy grids with child grids joined by a field, any nesting depth, inherited locale and theme, and lazy mounting.

Canonical: https://salmonui.dev/docs/data-grid/child-grids

`childGrid` renders a child `DataGrid` inside the detail row of each expanded
parent. It takes the child rows in `data` and every `DataGrid` prop of
the child; `joinField` names the field that relates parent and child rows,
or `parentField` and `childField` when the names differ.

```tsx
<DataGrid
  aria-label="Customers"
  data={customers}
  columns={customerColumns}
  childGrid={{
    data: orders,
    joinField: 'customerId',
    columns: orderColumns,
    childGrid: { data: items, parentField: 'id', childField: 'orderId', columns: itemColumns },
  }}
/>
```

Wrap a config in `defineChildGrid<Child, Parent>(config)` to type the child
rows in its callbacks; an inline object sees them as `unknown`. A child grid may have its own `childGrid`, to any depth. An array
is indexed once by the join value, so each child grid reads its rows in
constant time; a remote data source receives the relation as a filter
before the child grid's own filters, so the child grid cannot clear it.
`data` may also be a function that receives the parent
(`{ row, rowId, depth }`) and returns the child rows or a data source.

## Expanding, focus and inheritance

Child grids expand and collapse with the detail row methods and events.
They inherit `locale`, `dir`, `timeZone` and `currency` unless
set, the parent's `icons`, and the theme through CSS. A child
grid without `aria-label` or `aria-labelledby` is named by the
`childGridLabel` `localeText` key. Keys pressed inside a child grid
stay there; Tab moves in and out, Escape returns to the parent row.
`getChildGrid(rowId)` returns the API of a mounted child grid.

## Virtualization and export

A child grid mounts only when its detail row is rendered, so expanding every
parent of a large grid creates only the visible child grids. Excel and PDF exports nest the child rows of expanded parents
(`hierarchy: 'expanded'`, the default), of every parent (`'all'`) or none
(`'none'`). Every nested level is written: Excel puts each level one
column to the right and one outline level deeper (the sheet's outline
depth follows the deepest level), PDF draws each level as an indented
block under its row. Exports stop at 7 child levels, the Excel outline
limit; deeper child grids are left out. Nested levels follow the child
grid's own default expansion in `'expanded'` mode. `print()` takes the same
modes (`printing.hierarchy` or `print({ hierarchy })`) and prints each
child grid as a nested table.

### Live demo: Child grids

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

A three-level hierarchy grid (customers, orders, items) joined by field, with inherited locale, sortable child grids and lazy mounting.

`Demo.tsx`:

```tsx
'use client';

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

interface Customer {
  readonly customer: string;
  readonly country: string;
  readonly orders: number;
}

interface Item {
  readonly itemId: string;
  readonly orderId: string;
  readonly product: string;
  readonly quantity: number;
}

const orders = createOrders(2_000, 11);
const customers: Customer[] = [...new Map(orders.map((o) => [o.customer, o])).values()].map((o) => ({
  customer: o.customer,
  country: o.country,
  orders: orders.filter((x) => x.customer === o.customer).length,
}));
const items: Item[] = orders.flatMap((o, i) => [0, 1, 2].slice(0, 1 + (i % 3)).map((k) => ({ itemId: `${o.id}-${k}`, orderId: o.id, product: o.product, quantity: 1 + ((i + k) % 5) })));

const columns: DataGridColumn<Customer>[] = [
  { field: 'customer', header: 'Customer', primaryKey: true, width: 200 },
  { field: 'country', header: 'Country', width: 140 },
  { field: 'orders', header: 'Orders', type: 'number', align: 'end', width: 100 },
];

// Customers -> orders (joined on `customer`) -> items (joined on `orderId` = order `id`).
const childGrid = defineChildGrid<Order, Customer>({
  data: orders,
  joinField: 'customer',
  sorting: true,
  columns: [
    { field: 'id', header: 'Order', primaryKey: true, width: 110 },
    { 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 },
  ],
  childGrid: defineChildGrid<Item, Order>({
    data: items,
    parentField: 'id',
    childField: 'orderId',
    columns: [
      { field: 'itemId', header: 'Item', primaryKey: true, width: 130 },
      { field: 'product', header: 'Product', width: 150 },
      { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80 },
    ],
  }),
});

const LOCALE_OPTIONS = [
  { value: 'en-US', label: 'en-US' },
  { value: 'de-DE', label: 'de-DE' },
];

export default function ChildGridsDemo() {
  const api = useRef<DataGridApi<Customer> | null>(null);
  const [locale, setLocale] = useState('en-US');
  const [status, setStatus] = useState('');
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Locale
          <Select aria-label="Locale" data={LOCALE_OPTIONS} value={locale} onValueChange={(value) => value != null && setLocale(String(value))} />
        </label>
        <Button variant="outline" onClick={() => api.current?.expandDetail(customers[0]?.customer ?? '')}>
          Expand the first customer
        </Button>
        <Button
          variant="outline"
          onClick={async () => {
            const file = await api.current?.exportToCsv({ download: false, hierarchy: 'expanded' });
            setStatus(file ? `CSV: ${file.data.split('\n').length - 1} lines (CSV has no child rows; Excel and PDF nest them)` : '');
          }}
        >
          Export CSV
        </Button>
      </div>
      <DataGrid<Customer>
        key={locale}
        aria-label="Customers with orders"
        data={customers}
        columns={columns}
        height={460}
        locale={locale}
        currency="USD"
        timeZone="UTC"
        ref={api}
        childGrid={childGrid}
      />
      <p className="demo-status">
        Child grids inherit the locale (switch it to see the amounts reformat) and mount only when their row renders. {status}
      </p>
    </>
  );
}
```

## API reference

[`DataGridChildGrid`](https://salmonui.dev/docs/reference/data-grid/DataGridChildGrid)
lists the `childGrid` options,
[`DataGridChildGridParent`](https://salmonui.dev/docs/reference/data-grid/DataGridChildGridParent)
the parent passed to a `data` function, and
[`defineChildGrid`](https://salmonui.dev/docs/reference/data-grid/defineChildGrid) types a
config; `getChildGrid` and the detail methods are on
[`DataGridApi`](https://salmonui.dev/docs/reference/data-grid/DataGridApi).

### Live demo: Hierarchy print and export

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

Print and Excel export of a hierarchy grid and of detail template rows with the hierarchy modes expanded, all and none.

`Demo.tsx`:

```tsx
'use client';

import { useRef } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, defineChildGrid, type DataGridApi, type DataGridColumn, type DataGridExportWriters } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

type Mode = 'expanded' | 'all' | 'none';
const MODES: readonly Mode[] = ['expanded', 'all', 'none'];

const writers: DataGridExportWriters = { excel: () => import('@salmonui/export/xlsx') };

// Hierarchy grid: customers -> orders.
interface Customer {
  readonly customer: string;
  readonly country: string;
}
const orders = createOrders(60, 41);
const customers: Customer[] = [...new Map(orders.map((o) => [o.customer, { customer: o.customer, country: o.country }])).values()];
const customerColumns: DataGridColumn<Customer>[] = [
  { field: 'customer', header: 'Customer', primaryKey: true, width: 200 },
  { field: 'country', header: 'Country', width: 140 },
];
const childGrid = defineChildGrid<Order, Customer>({
  data: orders,
  joinField: 'customer',
  columns: [
    { field: 'id', header: 'Order', primaryKey: true, width: 110 },
    { field: 'product', header: 'Product', width: 150 },
    { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  ],
});

// Detail template grid: the `detail` export hook writes the template as text.
const detailOrders = orders.slice(0, 8);
const orderColumns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 160 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
];
const detailText = (order: Order) => [`${order.product} × ${order.quantity} to ${order.city}, ${order.country}`, order.note ? `Note: ${order.note}` : 'No note'];

export default function HierarchyOutputDemo() {
  const parents = useRef<DataGridApi<Customer> | null>(null);
  const details = useRef<DataGridApi<Order> | null>(null);
  const [log, push] = useEventLog();
  const report = (label: string, hierarchy: Mode, file: { data: Uint8Array } | null | undefined) =>
    push(`${label} Excel (${hierarchy}): ${file ? `${file.data.byteLength} bytes` : 'cancelled'}`);
  const exportCustomers = async (hierarchy: Mode) => report('customers', hierarchy, await parents.current?.exportToExcel({ download: false, hierarchy }));
  const exportOrders = async (hierarchy: Mode) =>
    report('orders', hierarchy, await details.current?.exportToExcel({ download: false, hierarchy, detail: ({ row }) => ({ text: detailText(row) }) }));
  return (
    <>
      <p className="demo-status">Hierarchy grid: the first customer is expanded.</p>
      <div className="demo-toolbar" aria-label="Hierarchy grid output">
        {MODES.map((mode) => (
          <Button key={`p-${mode}`} variant="outline" onClick={() => void parents.current?.print({ hierarchy: mode })}>
            Print customers ({mode})
          </Button>
        ))}
        {MODES.map((mode) => (
          <Button key={`x-${mode}`} variant="outline" onClick={() => void exportCustomers(mode)}>
            Excel customers ({mode})
          </Button>
        ))}
      </div>
      <DataGrid<Customer>
        aria-label="Customers with order child grids"
        data={customers}
        columns={customerColumns}
        childGrid={childGrid}
        defaultExpandedDetails={[customers[0]?.customer ?? '']}
        exportWriters={writers}
        height={300}
        locale="en-US"
        currency="USD"
        ref={parents}
        onAfterPrint={(e) => push(`printed customers (${e.hierarchy})`)}
      />
      <p className="demo-status">Detail template: the first two orders are expanded. The same detail hook writes the template text in print and export; expanded mode keeps the expanded orders only.</p>
      <div className="demo-toolbar" aria-label="Detail template output">
        {MODES.map((mode) => (
          <Button key={`dp-${mode}`} variant="outline" onClick={() => void details.current?.print({ hierarchy: mode, detail: ({ row }) => ({ text: detailText(row) }) })}>
            Print orders ({mode})
          </Button>
        ))}
        {MODES.map((mode) => (
          <Button key={`dx-${mode}`} variant="outline" onClick={() => void exportOrders(mode)}>
            Excel orders ({mode})
          </Button>
        ))}
      </div>
      <DataGrid<Order>
        aria-label="Orders with detail rows"
        data={detailOrders}
        columns={orderColumns}
        renderDetail={({ row }) => (
          <div className="demo-detail">
            {detailText(row).map((line) => (
              <p key={line}>{line}</p>
            ))}
          </div>
        )}
        detailHeight={70}
        defaultExpandedDetails={[detailOrders[0]?.id ?? '', detailOrders[1]?.id ?? '']}
        exportWriters={writers}
        height={300}
        locale="en-US"
        currency="USD"
        ref={details}
        onAfterPrint={(e) => push(`printed orders (${e.hierarchy})`)}
      />
      <EventLog entries={log} />
    </>
  );
}
```
