# Nested grids in master/detail

> Show each customer's orders in a nested grid, and each order's lines in a third level, with MasterDetailModule and correct cleanup.

A customer list that expands into that customer's orders, where each order expands into its lines, is a common back-office screen. Master/detail renders any DOM into a full-width panel, so each level is simply another Birch UI grid with its own `masterDetail` option.

> **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> Requires `MasterDetailModule` from `@birchui/grid-pro` in every grid that has detail panels.

## 1. The data

```ts title="customers.ts"
export interface OrderLine {
  sku: string;
  product: string;
  quantity: number;
  unitPrice: number;
}

export interface Order {
  id: string;
  orderedOn: string;
  status: 'Open' | 'Shipped' | 'Invoiced';
  total: number;
  lines: OrderLine[];
}

export interface Customer {
  id: string;
  name: string;
  country: string;
  accountManager: string;
  orders: Order[];
}
```

## 2. Build each level as a function

Writing each level as a function that mounts a grid into an element and returns its cleanup keeps the nesting readable:

```ts title="customer-grid.ts"
import { createGrid, type ColumnDef } from '@birchui/core';
import { MasterDetailModule } from '@birchui/grid-pro';
import type { Customer, Order, OrderLine } from './customers';

const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
const money = (value: unknown) => usd.format(Number(value));

const lineColumns: ColumnDef<OrderLine>[] = [
  { field: 'sku', header: 'SKU', width: 120 },
  { field: 'product', header: 'Product', flex: 1 },
  { field: 'quantity', header: 'Qty', type: 'number', width: 90 },
  { field: 'unitPrice', header: 'Unit price', type: 'number', format: money },
];

const orderColumns: ColumnDef<Order>[] = [
  { field: 'id', header: 'Order', width: 130 },
  { field: 'orderedOn', header: 'Ordered', type: 'date' },
  { field: 'status', header: 'Status' },
  { field: 'total', header: 'Total', type: 'number', format: money },
];

const customerColumns: ColumnDef<Customer>[] = [
  { field: 'name', header: 'Customer', flex: 1 },
  { field: 'country', header: 'Country', filter: 'set' },
  { field: 'accountManager', header: 'Account manager' },
  { id: 'orderCount', header: 'Orders', type: 'number', valueGetter: (customer) => customer.orders.length },
];

function mountLines(panel: HTMLElement, order: Order): () => void {
  const grid = createGrid<OrderLine>(panel, {
    columns: lineColumns,
    rows: order.lines,
    getRowId: (line) => line.sku,
    density: 'compact',
    ariaLabel: `Lines of order ${order.id}`,
  });
  return () => grid.destroy();
}

function mountOrders(panel: HTMLElement, customer: Customer): () => void {
  const grid = createGrid<Order>(panel, {
    columns: orderColumns,
    rows: customer.orders,
    getRowId: (order) => order.id,
    density: 'compact',
    ariaLabel: `Orders of ${customer.name}`,
    modules: [MasterDetailModule],
    masterDetail: {
      isExpandable: (order) => order.lines.length > 0,
      height: (order) => Math.min(72 + order.lines.length * 32, 260),
      render: (order, linesPanel) => mountLines(linesPanel, order),
    },
  });
  return () => grid.destroy();
}

export function mountCustomers(container: HTMLElement, customers: Customer[]) {
  return createGrid<Customer>(container, {
    columns: customerColumns,
    rows: customers,
    getRowId: (customer) => customer.id,
    ariaLabel: 'Customers',
    modules: [MasterDetailModule],
    masterDetail: {
      isExpandable: (customer) => customer.orders.length > 0,
      height: 340,
      render: (customer, ordersPanel) => mountOrders(ordersPanel, customer),
    },
  });
}
```

## 3. Open a panel from code

```ts
const customers = mountCustomers(document.querySelector<HTMLElement>('#customers')!, data);

customers.setDetailExpanded?.('CUST-0042', true);
```

## How it works

- `render` is called with the row and an empty panel element whenever the panel is rendered. The function it returns runs when the panel leaves the DOM: on collapse, when it scrolls out of the rendered window, and when the outer grid is destroyed. Destroying the outer grid therefore tears down every nested grid.
- Nested grids are independent. They have their own sorting, filtering, selection and keyboard focus. Keyboard input inside a panel stays in the panel.
- `height` is fixed per panel. The panel does not grow with its content, so size it from the data, as above, and let the nested grid scroll.

## Pitfalls

- **Panels are recreated.** Because rows are virtualized, a panel can be rendered several times. Keep state you need, such as a nested grid's sort, in your own map keyed by row id and apply it in `render`. `getState()` and `setState()` on the nested grid make that easy.
- **Every level needs the module.** A nested grid without `MasterDetailModule` ignores its `masterDetail` option.
- **License keys.** Set the key once with `setLicenseKey()` so nested grids are covered too, instead of passing `licenseKey` to the outer grid only.
- **Excel export** writes the master rows only; detail panels are not exported.

## Related

- [Master/detail](https://docs.birchui.com/grid-pro/master-detail.md) reference.
- [Persist grid state](https://docs.birchui.com/recipes/grid-persist-state.md) for saving the nested grids' state.
- [Activate your license key](https://docs.birchui.com/grid-pro/overview.md#activate-your-license-key).
