# Templates

> Cell, header and row templates, filter, pager, toolbar, editor and empty templates, per-row and per-cell attribute hooks, and the rules templates follow.

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

Templates are functions that return React nodes. String templates are not
supported; React escapes values by default.

## Cell and header templates

A column `renderCell` receives a context with the `row`,
its `rowId` and view `rowIndex`, the `column`, the raw `value`, the
`formattedValue`, and the `selected` and `editing` flags. A column
`renderHeader` receives `{ column, sortDirection,
sortIndex, filtered, grouped }` and replaces the header content while
sorting, resizing and reordering affordances stay in place.

```tsx
const columns: DataGridColumn<Order>[] = [
  {
    field: 'status',
    header: 'Status',
    renderCell: ({ value }) => <StatusBadge status={value as Status} />,
    renderHeader: ({ column, filtered }) => <>{column.header}{filtered ? ' (filtered)' : ''}</>,
    cellClassName: ({ value }) => (value === 'late' ? 'is-late' : undefined),
  },
];
```

Cells and headers accept extra attributes and class names: column
`cellProps` and `cellClassName` take a value or a function of the cell
context, and `headerProps` a value. The grid-level hooks `getRowProps(row,
rowIndex)`, `rowClassName(row, rowIndex)` and `getCellProps(ctx)` (the equivalents of `rowDataBound` and `queryCellInfo`)
return props instead of mutating the DOM, and run only for rendered rows and
cells, so their cost is bounded by the viewport, not the data size.

### Live demo: Cell and header templates

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

Function templates for cells and headers, per-cell attributes and classes, and per-row and per-cell hooks that run only for rendered rows.

`Demo.tsx`:

```tsx
'use client';

import { DataGrid, type DataGridColumn } from '@salmonui/data-grid';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(400);

const tone = { High: undefined, Normal: 'info', Low: 'success' } as const;

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  {
    field: 'customer',
    header: 'Customer',
    width: 170,
    // Cell template: receives row, value, formatted value, ids and index.
    renderCell: ({ row, rowIndex }) => (
      <span>
        <strong>{row.customer}</strong> <span aria-hidden="true">·</span> #{rowIndex + 1}
      </span>
    ),
  },
  {
    field: 'priority',
    header: 'Priority',
    width: 110,
    renderCell: ({ value }) => (
      <span className="demo-badge" data-tone={tone[value as Order['priority']]}>
        {String(value)}
      </span>
    ),
    // Header template: the sort, resize and reorder affordances stay.
    renderHeader: ({ column }) => (
      <span>
        {column.header} <span className="demo-badge" data-tone="info">tpl</span>
      </span>
    ),
  },
  {
    field: 'amount',
    header: 'Amount',
    type: 'number',
    format: 'C2',
    align: 'end',
    width: 120,
    // Per-cell attributes: a class and props computed from each cell's value.
    cellClassName: ({ value }) => ((value as number) > 900 ? 'demo-cell--negative' : undefined),
    cellProps: ({ formattedValue }) => ({ title: `Amount ${formattedValue}`, 'data-kind': 'amount' }),
    headerProps: { title: 'Order amount after discount' },
  },
  { field: 'city', header: 'City', width: 130 },
];

export default function CellTemplatesDemo() {
  return (
    <DataGrid<Order>
      aria-label="Orders with cell and header templates"
      data={orders}
      columns={columns}
      height={360}
      locale="en-US"
      currency="USD"
      timeZone="UTC"
      // Per-row and per-cell hooks run only for rendered rows and cells.
      getRowProps={(row) => (row.priority === 'High' ? { className: 'demo-row--flagged', 'data-priority': 'high' } : undefined)}
      getCellProps={(ctx) => (ctx.field === 'city' && ctx.row.country === 'Japan' ? { title: 'Ships from the Osaka warehouse' } : undefined)}
    />
  );
}
```

## Row templates

`renderRow` replaces the whole row element. Its context
is `{ row, rowId, rowIndex, defaultRow, rowProps, cells }`: the template
must spread `rowProps`, which carry `role="row"`, the ARIA row index and the
row id, and place `cells` inside; `defaultRow` is the built-in row,
to wrap instead of replace. Row templates work with row virtualization.

### Live demo: Row template with virtualization

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

A row template over 20,000 virtualized rows that keeps ARIA row and gridcell semantics; unshipped orders are flagged.

`Demo.tsx`:

```tsx
'use client';

import { DataGrid, type DataGridColumn } from '@salmonui/data-grid';
import { createOrders, type Order } from '../../lib/fixtures';

// 20,000 rows: the row template stays virtualized.
const orders = createOrders(20_000, 7);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 160 },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  { field: 'shipped', header: 'Shipped', width: 100 },
];

export default function RowTemplateDemo() {
  return (
    <DataGrid<Order>
      aria-label="Orders rendered through a row template"
      data={orders}
      columns={columns}
      height={360}
      locale="en-US"
      currency="USD"
      timeZone="UTC"
      // The template keeps the row element's role, aria-rowindex and ids by
      // spreading rowProps, and places the default cells inside it.
      renderRow={({ row, rowProps, cells }) => (
        <div {...rowProps} className={`${rowProps.className} demo-card-row`} data-shipped={row.shipped ? '' : undefined}>
          {cells}
        </div>
      )}
      rowClassName={(row) => (row.shipped ? undefined : 'demo-row--flagged')}
    />
  );
}
```

## Templates for the grid parts

Each grid part has a render prop with a typed context:

| Render prop | Context |
| --- | --- |
| column `renderEditor` | `{ value, setValue, inputProps, ... }` (see [Editing](https://salmonui.dev/docs/data-grid/editing)) |
| column `renderFilter` | `{ column, field, value, setValue, operator, operators, setOperator, apply, clear, editorProps }` |
| column `renderFilterCell` | the same context, for the filter row cell |
| `renderPager` | `{ page, pageSize, pageCount, totalRowCount, pageSizeOptions, goToPage, setPageSize, defaultPager }` |
| `renderToolbar` | `{ items, defaultToolbar, api }` (see [Toolbar](https://salmonui.dev/docs/data-grid/toolbar)) |
| `renderEmpty` | `{ reason: 'noData' \| 'noMatch' }` |
| `renderDetail` | `{ row, rowId, collapse, ... }` (see [Detail rows](https://salmonui.dev/docs/data-grid/detail-rows)) |

`renderFilter` replaces the value editor inside the filter menu: call
`setValue` to change the draft and let the user press OK, or `apply(value)`
to apply at once and close the menu. `renderPager` replaces the pager;
`defaultPager` is the built-in one, to wrap or decorate. `renderEmpty`
receives `noData` when there are no rows and `noMatch` when the search or
the filters match nothing.

### Live demo: Filter, pager and empty templates

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

A column `renderFilter` in the filter menu, a `renderPager` pager and a `renderEmpty` message for "no data" and "no match", all defined once at module scope.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { TextField } from '@salmonui/inputs/text-field';
import { DataGrid, type DataGridColumn, type DataGridEmptyContext, type DataGridFilterContext, type DataGridPagerContext } from '@salmonui/data-grid';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(200, 31);
const categories = ['Coffee', 'Tea', 'Equipment'] as const;

// Templates live at module scope: their identity is stable across renders, and
// they read everything from their context instead of React state.

/** Filter menu template: one button per category. */
function CategoryFilter({ value, apply, clear }: DataGridFilterContext<Order>) {
  return (
    <div className="demo-toolbar" role="group" aria-label="Category">
      {categories.map((p) => (
        <Button key={p} variant="outline" aria-pressed={value === p} onClick={() => apply(p)}>
          {p}
        </Button>
      ))}
      <Button variant="outline" onClick={clear}>
        Any
      </Button>
    </div>
  );
}

/** Pager template (`pagerTemplate`): the pager model and its actions. */
function renderPager({ page, pageCount, totalRowCount, goToPage }: DataGridPagerContext) {
  return (
    <nav className="demo-toolbar demo-pager" aria-label="Pages">
      <Button variant="outline" disabled={page <= 1} onClick={() => goToPage(page - 1)}>
        Previous
      </Button>
      <span className="demo-pager__status">
        Page {page} of {pageCount} ({totalRowCount} orders)
      </span>
      <Button variant="outline" disabled={page >= pageCount} onClick={() => goToPage(page + 1)}>
        Next
      </Button>
    </nav>
  );
}

/** Empty record template (`emptyRecordTemplate`). */
function renderEmpty({ reason }: DataGridEmptyContext) {
  return <div className="demo-empty">{reason === 'noMatch' ? 'No order matches the search or filters.' : 'There are no orders yet.'}</div>;
}

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'category', header: 'Category', width: 130, renderFilter: (ctx) => <CategoryFilter {...ctx} /> },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
];

const filtering = { ui: 'menu' } as const;
const paging = { pageSize: 10 };

export default function SlotTemplatesDemo() {
  const [text, setText] = useState('');
  const [empty, setEmpty] = useState(false);
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Search <TextField type="search" aria-label="Search orders" value={text} onValueChange={(value) => setText(value)} />
        </label>
        <Checkbox checked={empty} onCheckedChange={(checked) => setEmpty(checked)}>
          No data
        </Checkbox>
      </div>
      <DataGrid<Order>
        aria-label="Orders with filter, pager and empty templates"
        data={empty ? [] : orders}
        columns={columns}
        filtering={filtering}
        search={{ text }}
        paging={paging}
        renderPager={renderPager}
        renderEmpty={renderEmpty}
        height={320}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
      />
    </>
  );
}
```

## Rules for templates

Templates render inside the grid's virtualized rows, so they follow a few
rules:

- Define templates once, at module scope or in a memo, not inline in a
  component that re-renders often. Render-time functions (`renderCell`,
  `renderHeader`, `renderFilter`, `renderFilterCell`, `cellProps`,
  `cellClassName`, `headerProps`, `colSpan`, `rowSpan`) never recompile
  columns, but other function fields (`valueGetter`, `valueFormatter`,
  `sortComparator`, ...) compare by identity and recompile the column when
  they change. Data Grid-level templates (`renderRow`, `renderEmpty`,
  `getRowProps`, `rowClassName`, `getCellProps`) re-render every visible
  cell when their identity changes. Development builds report a template
  whose identity changes on three consecutive commits through `onWarning`
  (code `template-identity-unstable`).
- Read everything from the context. Do not put scroll positions, pointer
  coordinates, drag state or other high-frequency values into React state
  for a template to read: the grid keeps those transients outside React, and
  a state update per scroll frame would re-render every visible cell.
- Keep templates pure: no side effects while rendering, and no module-level
  mutable state, so they stay SSR- and React Compiler-safe. Effects inside a
  template component run when the row mounts and unmount when it scrolls
  out of the rendered window.

## API reference

[`DataGridColumn`](https://salmonui.dev/docs/reference/data-grid/DataGridColumn) lists the
column render props and attribute hooks, and
[`DataGridProps`](https://salmonui.dev/docs/reference/data-grid/DataGridProps) the grid
ones; the contexts are
[`DataGridCellContext`](https://salmonui.dev/docs/reference/data-grid/DataGridCellContext),
[`DataGridHeaderContext`](https://salmonui.dev/docs/reference/data-grid/DataGridHeaderContext),
[`DataGridRowContext`](https://salmonui.dev/docs/reference/data-grid/DataGridRowContext),
[`DataGridFilterContext`](https://salmonui.dev/docs/reference/data-grid/DataGridFilterContext),
[`DataGridPagerContext`](https://salmonui.dev/docs/reference/data-grid/DataGridPagerContext)
and [`DataGridEmptyContext`](https://salmonui.dev/docs/reference/data-grid/DataGridEmptyContext).
Per-row and per-cell attributes (`getRowProps`, `getCellProps`) are covered
in [Events](https://salmonui.dev/docs/data-grid/events).
