# Templates

> Render props for options, the value, chips, group headers, the popup header and footer, and the empty, error and loading states of Select and Combobox.

Canonical: https://salmonui.dev/docs/dropdowns/dropdown-templates

Every template is a function render prop or a `ReactNode`. The
table covers `Select` and `Combobox` (both take the same render props);
`Listbox`, `TreeSelect` and `Mention` have their own `renderItem`,
`renderEmpty`, `renderError` and `renderLoading`, described in their API
references.

| Part | Template |
| --- | --- |
| Option | `renderItem({ item, label, selected, active, disabled, matches })`, rendered inside the `role="option"` element, which keeps its role and state; `getItemIcon(item)` adds an icon; `getItemProps(item)` adds `className`, `style` and `data-*` to rendered options |
| Selected value | `renderValue({ items, labels })`; chips of `Combobox multiple`: `renderChip({ item, label, remove, disabled })`, and `getChipProps(item)` adds `className`, `style` and `data-*` |
| Group header | `renderGroupHeader({ group })` for inline and sticky headers |
| Popup header and footer | `popupHeader`, `popupFooter` |
| Empty list | `renderEmpty({ reason: 'noData' \| 'noMatch' })`; default `localeText.noData` / `noResults` |
| Load error | `renderError({ error, retry })`; default `localeText.loadError` with a Retry button; `onLoadError(error)` |
| Loading | `renderLoading()`; the list carries `aria-busy` while loading |

```tsx
import { Select } from '@salmonui/dropdowns/select';
import '@salmonui/dropdowns/select/styles.css';

<Select
  aria-label="Owner"
  data={people}
  getItemValue={(p) => p.id}
  getItemLabel={(p) => p.name}
  getItemIcon={(p) => <img src={p.photo} alt="" width={20} height={20} />}
  renderItem={({ item, label }) => (
    <>
      {label} <small>{item.role}</small>
    </>
  )}
  renderValue={({ items }) => <strong>{items[0]?.name}</strong>}
  renderEmpty={({ reason }) => (reason === 'noMatch' ? 'Nobody by that name' : 'No people yet')}
/>
```

`matches` holds `[start, end)` ranges of the search text in `label`, so a
custom option can mark matches the way `highlightMatches` does. Render props
run for rendered options only (the list is windowed above 100 items).

## No string templates

- String and element-id templates:
  `'${Name}'` and `'#template'` need a runtime template compiler (string
  evaluation, blocked by a strict CSP) and cannot be type-checked, so
  templates are render props only. To bold a field, write
  `renderItem={({ item }) => <b>{item.Name}</b>}`.
- HTML sanitizing and encoding: React
  escapes text and no dropdown renders HTML strings, so there is nothing to
  sanitize or encode and no option for it. Build markup in a render prop,
  and own any `dangerouslySetInnerHTML` call for trusted HTML.

See the API reference of [`select`](https://salmonui.dev/docs/reference/dropdowns/select) and
[`combobox`](https://salmonui.dev/docs/reference/dropdowns/combobox).

### Live demo: Dropdown templates

Live demo: https://salmonui.dev/demos/dropdowns/dropdown-templates

Custom options, value, group headers, popup header and footer, and the empty, loading and error states of Select and Combobox.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Combobox } from '@salmonui/dropdowns/combobox';
import { Select } from '@salmonui/dropdowns/select';
import { createDemoListSource } from '../../lib/demo-list-source';

interface Person {
  readonly value: string;
  readonly label: string;
  readonly role: string;
  readonly team: string;
}

// Sorted by team: items of one group must be contiguous.
const PEOPLE: Person[] = [
  { value: 'ana', label: 'Ana Lima', role: 'Designer', team: 'Design' },
  { value: 'ben', label: 'Ben Okafor', role: 'Researcher', team: 'Design' },
  { value: 'chen', label: 'Chen Wei', role: 'Frontend engineer', team: 'Engineering' },
  { value: 'dara', label: 'Dara Holm', role: 'Backend engineer', team: 'Engineering' },
  { value: 'emil', label: 'Emil Novak', role: 'Site reliability', team: 'Engineering' },
  { value: 'fay', label: 'Fay Ito', role: 'Product manager', team: 'Product' },
];

function initials(label: string): string {
  return label
    .split(' ')
    .map((part) => part[0])
    .join('');
}

function Highlight({ text, ranges }: { text: string; ranges: readonly (readonly [number, number])[] }) {
  if (ranges.length === 0) return <>{text}</>;
  const parts = [];
  let at = 0;
  for (const [start, end] of ranges) {
    parts.push(text.slice(at, start), <mark key={start}>{text.slice(start, end)}</mark>);
    at = end;
  }
  parts.push(text.slice(at));
  return <>{parts}</>;
}

export default function DropdownTemplatesDemo() {
  const failNext = useRef(false);
  // A slow remote source (1.5 s) whose reads can be made to fail.
  const [slow] = useState(() =>
    createDemoListSource<Person>({
      rows: PEOPLE,
      latency: 1500,
      shouldFail: () => failNext.current,
    }),
  );
  const [fail, setFail] = useState(false);
  return (
    <div style={{ display: 'grid', gap: 16, maxWidth: 420 }}>
      <div style={{ display: 'grid', gap: 4 }}>
        <span id="dd-tpl-owner">Owner</span>
        <Select<Person>
          aria-labelledby="dd-tpl-owner"
          data={PEOPLE}
          defaultValue="chen"
          getItemGroup={(person) => person.team}
          renderGroupHeader={({ group }) => <strong>{group} team</strong>}
          renderItem={({ item, selected }) => (
            <span style={{ display: 'flex', gap: 8, alignItems: 'center', paddingBlock: 4 }}>
              <span aria-hidden="true" style={{ inlineSize: 24, blockSize: 24, borderRadius: 'var(--salmon-radius-full)', display: 'grid', placeItems: 'center', fontSize: 11, background: 'var(--salmon-surface-sunken)' }}>
                {initials(item.label)}
              </span>
              <span>
                {item.label}
                {selected ? ' (owner)' : ''}
                <br />
                <small>{item.role}</small>
              </span>
            </span>
          )}
          renderValue={({ items }) => (items[0] ? <span>{items[0].label} · <small>{items[0].role}</small></span> : null)}
          popupHeader={<small style={{ display: 'block' }}>Pick the person accountable for this task</small>}
          popupFooter={<small style={{ display: 'block' }}>{PEOPLE.length} people in 3 teams</small>}
        />
      </div>
      <div style={{ display: 'grid', gap: 4 }}>
        <span id="dd-tpl-search">Reviewer (type something nobody is called, such as "zz")</span>
        <Combobox<Person>
          aria-labelledby="dd-tpl-search"
          data={PEOPLE}
          searchOperator="contains"
          renderItem={({ label, matches }) => <Highlight text={label} ranges={matches} />}
          renderEmpty={({ reason }) => <em>{reason === 'noMatch' ? 'Nobody by that name' : 'No people yet'}</em>}
        />
      </div>
      <div style={{ display: 'grid', gap: 8 }}>
        <Checkbox
          checked={fail}
          onCheckedChange={(checked) => {
            failNext.current = checked;
            setFail(checked);
          }}
        >
          Make reads fail
        </Checkbox>
        <div style={{ display: 'grid', gap: 4 }}>
          <span id="dd-tpl-remote">Assignee (remote, 1.5 s)</span>
          <Select<Person>
            aria-labelledby="dd-tpl-remote"
            data={slow}
            placeholder="Open to load people"
            renderLoading={() => <span role="status">Fetching the team directory…</span>}
            renderError={({ retry }) => (
              <span role="alert" style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                The directory is unavailable.
                <Button variant="outline" onClick={retry}>
                  Try again
                </Button>
              </span>
            )}
          />
        </div>
      </div>
    </div>
  );
}
```
