# Appearance and templates

> The whitelisted display props, renderCell, renderHeader, getCellClassName and renderTooltip, a hyperlink recipe with onCellClick, and cell selection with its events.

Canonical: https://salmonui.dev/docs/pivot-table/appearance

## Display props

`PivotTable` renders through the Data Grid renderer but does not pass its
settings through. A whitelist of display props
is forwarded:

| Prop | Default |
| --- | --- |
| `rowHeight` | the Data Grid default |
| `columnWidth` | 120 |
| `rowHeaderWidth` | 220 (compact), 150 per column (tabular) |
| `height` | 400 |
| `resizable`, `reorderable` | off |
| `textWrap` | off |
| `overflow` | the Data Grid default |
| `gridLines` | `'both'` |
| `striped`, `highlightOnHover` | off, Data Grid default |
| `emptyCellText` | `''` |

Subtotal and grand total rows carry `salmon-pivot-table-subtotal-row` and
`salmon-pivot-table-grand-total-row`; colors come from the theme seeds.
Number and date formats are model data (`pivotModel.formats`,
[Editors](https://salmonui.dev/docs/pivot-table/editors)).

## Templates

| Prop | Context |
| --- | --- |
| `renderCell(ctx)` | `{ cell, rowHeader, columnHeader, selected, defaultContent }` |
| `renderHeader(ctx)` | `{ header, axis, defaultContent }` |
| `getCellClassName(ctx)` | as `renderCell`; returns a class string |
| `renderTooltip(ctx)` | `{ cell, rowHeader, columnHeader }` |

`cell` is the engine's `PivotCell`: `value`, `formattedValue`, `kind`
(`value`, `subtotal`, `grandTotal`), `rowKey`, `columnKey`, `measure` and
`rowCount`. `defaultContent` is the formatted value (or `emptyCellText`),
so a template can wrap it instead of formatting again:

```tsx
const renderCell = ({ cell, defaultContent }: PivotCellContext) =>
  cell.value !== null && cell.value < 0 ? <span className="negative">{defaultContent}</span> : defaultContent;

<PivotTable pivot={pivot} renderCell={renderCell} />
```

Columns are rebuilt when a render prop changes identity, so define render
props at module level or memoize them. Templates return React elements;
no HTML strings are rendered. To change the value itself (not only its
display) use `getCellValue` ([Aggregation](https://salmonui.dev/docs/pivot-table/aggregation)).

## Hyperlinks

To show links, render a link in `renderCell` or `renderHeader` and handle
the click in `onCellClick`:

```tsx
const renderHeader = ({ header, axis, defaultContent }: PivotHeaderContext) =>
  axis === 'rows' && header.field === 'country' ? <a href={`/countries/${header.label}`}>{defaultContent}</a> : defaultContent;

<PivotTable
  pivot={pivot}
  renderHeader={renderHeader}
  onCellClick={(event) => {
    // event.cell is null on a row header; event.rowHeader is the row's member.
    if (event.cell && event.cell.value !== null && event.cell.value > 10_000) openDetails(event.rowKey, event.columnKey);
  }}
/>
```

Any condition (all cells, row or column headers, value cells, by value or
by header text) is a branch in the render prop.

## Selection

Cell selection is off by default:

```tsx
<PivotTable
  data={data}
  defaultPivotModel={model}
  selection={{ multiple: true }}           // or `selection` for multiple cells, `{ multiple: false }` for one
  onBeforeSelectionChange={(event) => {}}  // preventDefault() cancels
  onSelectionChange={(event) => console.log(event.keys)}
/>
```

With a shared store (`pivot={pivot}`), pass `onBeforeSelectionChange` and
`onSelectionChange` to `usePivot()` instead: the store fires them.

Ranges select as a box (drag, Shift+click, Shift+arrows). Selected cells
are keyed `rowKey|columnKey` (`event.cells` holds `{ rowKey, columnKey }`
pairs) and stored in the pivot store (`usePivotState(pivot, (s) =>
s.selection)`), so they survive scrolling and re-renders.

## HTML strings and class names

Salmon UI never renders HTML strings and React escapes text, so there is no
HTML sanitizer option and no string templates, which would need a runtime
compiler that breaks a strict CSP. Use `renderCell`,
`renderHeader`, `renderTooltip` and `renderLoading` for custom content;
toolbar items can render React content. Style the root with `className`.

### Live demo: Cell templates and conditional formats

Live demo: https://salmonui.dev/demos/pivot-table/pivot-table-templates

Custom value and header content, a hyperlink row header handled by onCellClick, class names per cell, tooltips, conditional format tones and box cell selection.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { PivotTable, type PivotCellContext, type PivotHeaderContext, type PivotModelInput, type PivotTooltipContext, type PivotFieldDefinition } from '@salmonui/pivot-table';

type Sale = { region: string; country: string; year: string; amount: number };

const COUNTRIES: Record<string, string[]> = { Asia: ['Japan', 'India'], Europe: ['France', 'Germany'], Americas: ['Brazil', 'Canada'] };

function makeSales(): Sale[] {
  const rows: Sale[] = [];
  let n = 0;
  for (const [region, countries] of Object.entries(COUNTRIES)) {
    for (const country of countries) {
      for (const year of ['2024', '2025', '2026']) {
        for (let k = 0; k < 3; k++) {
          n++;
          rows.push({ region, country, year, amount: ((n * 397) % 1400) + 150 });
        }
      }
    }
  }
  return rows;
}

const SALES = makeSales();

// Conditional formats are part of the report model: tones come from the theme seeds.
// Captions for the headers, the axis bar and the field list (the raw field names otherwise).
const FIELDS: PivotFieldDefinition<Sale>[] = [
  { field: 'region', caption: 'Region', type: 'string' },
  { field: 'country', caption: 'Country', type: 'string' },
  { field: 'year', caption: 'Year', type: 'string' },
  { field: 'amount', caption: 'Amount', type: 'number' },
];

const MODEL: PivotModelInput = {
  rows: [{ field: 'region' }, { field: 'country' }],
  columns: [{ field: 'year' }],
  values: [{ field: 'amount', aggregate: 'sum' }],
  expanded: 'all',
  formats: { amount: { number: { style: 'currency', currency: 'USD', maximumFractionDigits: 0 } } },
  conditionalFormats: [
    { measure: 'amount', operator: 'greaterThanOrEqual', value: 3000, tone: 'success', applyGrandTotals: false },
    { measure: 'amount', operator: 'lessThan', value: 1800, tone: 'danger', applyGrandTotals: false },
  ],
};

// Render props are module-level (stable identities), so columns are not rebuilt on every render.
const renderCell = ({ cell, defaultContent }: PivotCellContext) => (cell.kind === 'grandTotal' ? <strong>{defaultContent}</strong> : defaultContent);

// Hyperlink recipe: country headers render as links; `onCellClick` handles the click.
const renderHeader = ({ header, axis, defaultContent }: PivotHeaderContext) =>
  axis === 'rows' && header.field === 'country' && header.kind === 'member' ? (
    <a href={`?country=${encodeURIComponent(header.label.toLowerCase())}`} onClick={(event) => event.preventDefault()}>
      {defaultContent}
    </a>
  ) : (
    defaultContent
  );

const renderTooltip = ({ cell, rowHeader, columnHeader }: PivotTooltipContext) => `${rowHeader.label} · ${columnHeader.label}: ${cell.formattedValue} (${cell.rowCount} rows)`;

const getCellClassName = ({ cell }: PivotCellContext) => (cell.kind === 'subtotal' ? 'demo-pivot-subtotal' : '');

/** renderCell, renderHeader, getCellClassName, conditional formats, a hyperlink header and cell selection. */
export default function PivotTableTemplatesDemo() {
  const [clicked, setClicked] = useState('nothing yet');
  const [selected, setSelected] = useState(0);
  return (
    <div>
      <PivotTable<Sale>
        data={SALES}
        fields={FIELDS}
        defaultPivotModel={MODEL}
        locale="en-US"
        height={340}
        columnWidth={130}
        rowHeaderWidth={180}
        striped
        highlightOnHover
        gridLines="horizontal"
        selection={{ multiple: true }}
        renderCell={renderCell}
        renderHeader={renderHeader}
        getCellClassName={getCellClassName}
        renderTooltip={renderTooltip}
        onCellClick={(event) => setClicked(event.cell ? `${event.cell.formattedValue} at ${event.rowKey} × ${event.columnKey}` : `row header ${event.rowHeader.label}`)}
        onSelectionChange={(event) => setSelected(event.keys.length)}
        aria-label="Sales with templates"
      />
      <p className="demo-status" aria-live="polite">
        Clicked: <code>{clicked}</code> · {selected} cell(s) selected
      </p>
    </div>
  );
}
```
