# List

> The display list for read-only content, a server-component ul or ol with item rows that compose Avatar and badges; selection lists are Listbox.

Canonical: https://salmonui.dev/docs/layout/list

`List` is a styled `<ul>` (or `<ol>` with `ordered`) for content that is
only displayed. It has no JavaScript behavior and renders in React Server
Components. It lives in `@salmonui/layout/list` with its own stylesheet.

```tsx
import { List, ListItem } from '@salmonui/layout/list';
import { Avatar } from '@salmonui/layout/avatar';
import '@salmonui/layout/list/styles.css';
import '@salmonui/layout/avatar/styles.css';

<List aria-label="People">
  <ListItem>
    <Avatar name="Ada Lovelace" size="sm" shape="circle" />
    Ada Lovelace
    <span className="salmon-list-item-description">Mathematician</span>
  </ListItem>
</List>;
```

### Live demo: List

Live demo: https://salmonui.dev/demos/layout/list

A display List of people with avatars and secondary lines, and an invitations List whose items hold Accept and Decline buttons.

`Demo.tsx`:

```tsx
'use client';
import { useState } from 'react';
import { Avatar } from '@salmonui/layout/avatar';
import { Button } from '@salmonui/buttons/button';
import { List, ListItem } from '@salmonui/layout/list';

const PEOPLE = [
  ['Ada Lovelace', 'Mathematician'],
  ['Alan Turing', 'Computer scientist'],
  ['Grace Hopper', 'Rear admiral'],
] as const;

const INVITES = ['Edsger Dijkstra', 'Barbara Liskov'] as const;

export default function ListDemo() {
  const [answers, setAnswers] = useState<Record<string, string>>({});
  return (
    <div style={{ display: 'grid', gap: 16, maxWidth: 420 }}>
      <List aria-label="People">
        {PEOPLE.map(([name, role]) => (
          <ListItem key={name}>
            <Avatar name={name} size="sm" shape="circle" />
            {/* Name and role stack beside the avatar. */}
            <span style={{ display: 'grid' }}>
              {name}
              <span className="salmon-list-item-description">{role}</span>
            </span>
          </ListItem>
        ))}
      </List>
      <List aria-label="Invitations">
        {INVITES.map((name) => (
          <ListItem key={name}>
            <Avatar name={name} size="sm" shape="circle" />
            {name}
            {answers[name] ? (
              <span className="salmon-list-item-description" style={{ flexBasis: 'auto', marginInlineStart: 'auto' }}>
                {answers[name]}
              </span>
            ) : (
              <span style={{ display: 'inline-flex', gap: 8, marginInlineStart: 'auto' }}>
                <Button variant="outline" aria-label={`Decline ${name}`} onClick={() => setAnswers({ ...answers, [name]: 'Declined' })}>
                  Decline
                </Button>
                <Button tone="primary" aria-label={`Accept ${name}`} onClick={() => setAnswers({ ...answers, [name]: 'Accepted' })}>
                  Accept
                </Button>
              </span>
            )}
          </ListItem>
        ))}
      </List>
    </div>
  );
}
```

- `.salmon-list-item` is a wrapping flex row, so an `Avatar`, the text and
  a trailing badge or time line up; a child with
  `.salmon-list-item-description` wraps onto its own secondary line.
- Items are separated by a thin line.
- `List.Item` is the same component as `ListItem`.

`List` is for display only. A list the user selects from, checks or navigates with the arrow keys is
`Listbox` ([Listbox](https://salmonui.dev/docs/dropdowns/listbox)), which carries the APG
Listbox keyboard model, selection, virtualization and remote data.

## Interactive items

Items may hold controls: buttons inside a `ListItem` stay in the page's
Tab order, with no roving focus to learn.

```tsx
import { Button } from '@salmonui/buttons/button';

<List aria-label="Invitations">
  <ListItem>
    <Avatar name="Ada Lovelace" size="sm" shape="circle" />
    Ada Lovelace
    <Button size="sm" variant="outline">Accept</Button>
  </ListItem>
</List>
```

## Selectable lists

A selectable list is a `Listbox` from `@salmonui/dropdowns/listbox`. Its props
cover the list features:

- `data` takes objects, strings or numbers; a primitive is its own value
  and label. It can also be an `@salmonui/data` source with
  `query`: range reads, abortable.
- `getItemValue`, `getItemLabel` and `getItemGroup` read the item fields;
`getItemIcon` adds an icon; `isItemDisabled`
  disables items reactively.
- `getItemProps` sets per-item attributes (`title`, `className`, `style`,
  `data-*`).
- `getItemGroup` with `renderGroupHeader` groups items; group headers are
  sticky when virtualized.
- `renderItem({ item, label, selected, active, disabled })` renders each
  item.
- `value` / `defaultValue` / `onValueChange` (`event.items`) hold the
  selection; `multiple` with an array `value` selects several
  items.
- `indicator="checkbox"` shows checkboxes, with
  `indicatorPosition: 'start' | 'end'` (logical, mirrors in RTL); check items through a
  controlled `value`, `showSelectAll` or Ctrl+A.
- `virtualization` renders only the visible items (fixed item height; on
  above 100 items); `maxVisibleItems`, `style` and `className`
  size the list.
- Loading and errors: `aria-busy` with `renderLoading`,
  `renderError({ error, retry })`, `onLoadError` and `renderEmpty`.
A remote source loads ranges while scrolling, and `onScroll`
  passes through.
- The keyboard follows APG Listbox: arrows, Home / End, Space, Ctrl+A,
  Shift+arrows and type-ahead.
- `disabled` disables the whole list; `className` /
  `classNames` / `styles`, the inherited `dir` and `localeText` cover
  styling, RTL and localization.

```tsx
import { Listbox } from '@salmonui/dropdowns/listbox';
import '@salmonui/dropdowns/listbox/styles.css';

<Listbox
  aria-label="Contacts"
  data={contacts}
  getItemValue={(c) => c.id}
  getItemLabel={(c) => c.name}
  getItemGroup={(c) => c.team}
  getItemProps={(c) => ({ title: c.email })}
  multiple
  indicator="checkbox"
  value={checked}
  onValueChange={setChecked}
/>
```

### Live demo: ListView as Listbox

Live demo: https://salmonui.dev/demos/layout/listview

A grouped, checkable contact list with item templates, tooltips and a disabled item, written with Listbox.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Avatar } from '@salmonui/layout/avatar';
import { Listbox, type ListboxKey } from '@salmonui/dropdowns/listbox';

interface Contact {
  id: number;
  name: string;
  team: string;
  email: string;
  away?: boolean;
}

// A Listbox with groups, an item template, tooltips and checkboxes:
// accessors read the item fields, `renderItem` renders each item.
const contacts: Contact[] = [
  { id: 1, name: 'Ada Lovelace', team: 'Engineering', email: 'ada@example.com' },
  { id: 2, name: 'Alan Turing', team: 'Engineering', email: 'alan@example.com' },
  { id: 3, name: 'Edsger Dijkstra', team: 'Engineering', email: 'edsger@example.com', away: true },
  { id: 4, name: 'Grace Hopper', team: 'Operations', email: 'grace@example.com' },
  { id: 5, name: 'Barbara Liskov', team: 'Operations', email: 'barbara@example.com' },
];

export default function ListViewDemo() {
  const [checked, setChecked] = useState<readonly ListboxKey[]>([1, 4]);
  return (
    <div style={{ display: 'grid', gap: 12, maxInlineSize: 360 }}>
      <Listbox
        aria-label="Contacts"
        data={contacts}
        getItemValue={(c) => c.id}
        getItemLabel={(c) => c.name}
        getItemGroup={(c) => c.team}
        isItemDisabled={(c) => c.away === true}
        getItemProps={(c) => ({ title: c.email })}
        renderItem={({ label }) => (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <Avatar name={label} size="xs" shape="circle" />
            {label}
          </span>
        )}
        multiple
        indicator="checkbox"
        showSelectAll
        value={checked}
        onValueChange={setChecked}
      />
      <p style={{ margin: 0 }}>Checked: {checked.length}</p>
    </div>
  );
}
```

Checkboxes at the inline end are `indicatorPosition="end"`; the position
is logical, so RTL mirrors it.

Icons, per-item attributes, single selection, a fixed height and the
disabled state:

### Live demo: ListView icons, item attributes and single selection

Live demo: https://salmonui.dev/demos/layout/listview-options

A folder Listbox with item icons, per-item class, title and data attributes, single selection with a change log, a fixed height in items, a disabled switch and right-to-left.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Listbox, type ListboxKey } from '@salmonui/dropdowns/listbox';
import { EventLog, useEventLog } from '../../components/demo-kit';

interface Folder {
  value: string;
  label: string;
  unread: number;
}

const FOLDERS: Folder[] = [
  { value: 'inbox', label: 'Inbox', unread: 12 },
  { value: 'drafts', label: 'Drafts', unread: 0 },
  { value: 'sent', label: 'Sent', unread: 0 },
  { value: 'archive', label: 'Archive', unread: 0 },
  { value: 'spam', label: 'Spam', unread: 3 },
  { value: 'trash', label: 'Trash', unread: 0 },
  { value: 'receipts', label: 'Receipts', unread: 1 },
  { value: 'travel', label: 'Travel', unread: 0 },
];

// 16 px outline icons (paths in a 16 x 16 box), drawn in the item's text color.
const ICONS: Record<string, string> = {
  inbox: 'M2 9.5h3.5l1 1.5h3l1-1.5H14M3.5 3h9L14 9.5V13H2V9.5z',
  drafts: 'M10.5 2.5l3 3L6 13H3v-3z M9 4l3 3',
  sent: 'M2 8l12-5.5L10.5 14 8 9z M8 9l6-6.5',
  archive: 'M2 3h12v3H2z M3 6v7h10V6 M6.5 8.5h3',
  spam: 'M8 2a6 6 0 1 0 0 12A6 6 0 1 0 8 2z M3.8 3.8l8.4 8.4',
  trash: 'M2.5 4h11 M6 4V2.5h4V4 M4 4l.7 9.5h6.6L12 4',
  receipts: 'M3.5 2h9v12l-1.5-1-1.5 1-1.5-1-1.5 1-1.5-1-1.5 1z M6 5.5h4 M6 8h4',
  travel: 'M14 8l-5.5-1.5L6.5 2H5l1 4.5-3 .5-1-1.5H1L2 8l-1 2.5h1l1-1.5 3 .5-1 4.5h1.5l2-4.5z',
};

// Module-scope accessors stay stable across renders.
const icon = (f: Folder) => (
  <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="none" stroke="currentColor" strokeWidth="1.25" strokeLinejoin="round">
    <path d={ICONS[f.value]} />
  </svg>
);
const itemProps = (f: Folder) => (f.unread > 0 ? { className: 'demo-listbox-unread', 'data-unread': f.unread, title: `${f.unread} unread` } : undefined);

// A Listbox with item icons, per-item attributes, single selection and
// a fixed height; the controls switch `disabled` and RTL.
export default function ListViewOptionsDemo() {
  const [folder, setFolder] = useState<ListboxKey | null>('inbox');
  const [disabled, setDisabled] = useState(false);
  const [rtl, setRtl] = useState(false);
  const [log, push] = useEventLog(6);
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <div className="demo-toolbar">
        <Checkbox checked={disabled} onCheckedChange={(checked) => setDisabled(checked)}>
          Disabled
        </Checkbox>
        <Checkbox checked={rtl} onCheckedChange={(checked) => setRtl(checked)}>
          Right to left
        </Checkbox>
      </div>
      <div dir={rtl ? 'rtl' : 'ltr'} style={{ display: 'grid', gap: 8 }}>
        <p id="listview-options-label" className="salmon-field-label" style={{ margin: 0 }}>
          Folders
        </p>
        <Listbox<Folder>
          aria-labelledby="listview-options-label"
          data={FOLDERS}
          getItemIcon={icon}
          getItemProps={itemProps}
          maxVisibleItems={5}
          style={{ inlineSize: 240 }}
          disabled={disabled}
          name="folder"
          value={folder}
          onValueChange={(value, event) => {
            setFolder(value);
            push(`${event.reason} ${String(value)} (${event.source}); item: ${event.items[0]?.label ?? 'none'}`);
          }}
        />
        <p style={{ margin: 0 }}>
          Folder: <output>{String(folder)}</output>
        </p>
      </div>
      <EventLog entries={log} label="Selection events" />
    </div>
  );
}
```

A remote source read in ranges, with virtualization, loading and error
states:

### Live demo: Remote ListView as Listbox

Live demo: https://salmonui.dev/demos/layout/listview-remote

A virtualized Listbox over 2,000 tickets read in ranges from a remote source with latency, a base query filter, a loading spinner, and an error state with Retry.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Listbox, type ListboxDataSource, type ListboxKey, type ListboxQuery } from '@salmonui/dropdowns/listbox';
import { Spinner } from '@salmonui/notifications/spinner';
import { EventLog, useEventLog } from '../../components/demo-kit';

interface Ticket {
  id: number;
  label: string;
  status: 'open' | 'closed';
}

// Base query merged into every read.
const OPEN_ONLY: ListboxQuery = { filters: [{ columnId: 'status', operator: 'equal', value: 'open', predicate: 'and', source: 'api' }] };

const ALL: ListboxQuery = {};

// Accessors stay stable at module scope.
const ticketId = (t: Ticket) => t.id;

const TICKETS: Ticket[] = Array.from({ length: 2000 }, (_, i) => ({ id: i + 1, label: `Ticket #${String(i + 1).padStart(4, '0')}`, status: i % 3 === 0 ? 'closed' : 'open' }));

// A fake remote endpoint with 400 ms of latency:
// it answers the requested `range`, applies the base `query` filter, and fails
// on demand so the error state and Retry can be tried.
function createTickets(push: (entry: string) => void, failNext: { current: boolean }): ListboxDataSource<Ticket> {
  return {
    read(request) {
      const status = request.query.filters?.find((f) => f.kind !== 'group' && f.columnId === 'status');
      const wanted = status && status.kind !== 'group' ? String(status.value) : null;
      const start = request.range?.start ?? 0;
      const end = request.range?.end ?? 50;
      push(`read ${start}–${end}${wanted ? ` (status = ${wanted})` : ''}`);
      return new Promise((resolve, reject) => {
        const timer = setTimeout(() => {
          if (failNext.current) {
            failNext.current = false;
            push('read failed');
            reject(new Error('The ticket service did not answer'));
            return;
          }
          const rows = wanted ? TICKETS.filter((t) => t.status === wanted) : TICKETS;
          resolve({ version: request.version, rows: rows.slice(start, end), totalRowCount: rows.length });
        }, 400);
        request.signal.addEventListener('abort', () => {
          clearTimeout(timer);
          reject(new DOMException('Aborted', 'AbortError'));
        });
      });
    },
  };
}

export default function ListViewRemoteDemo() {
  const [log, push] = useEventLog(8);
  const [failNext] = useState(() => ({ current: false }));
  // Created once: a new source per render would restart the reads.
  const [tickets] = useState(() => createTickets(push, failNext));
  const [openOnly, setOpenOnly] = useState(false);
  const [value, setValue] = useState<ListboxKey | null>(null);
  return (
    <div style={{ display: 'grid', gap: 12, maxInlineSize: 420 }}>
      <div className="demo-toolbar">
        <Checkbox checked={openOnly} onCheckedChange={(checked) => setOpenOnly(checked)}>
          Open tickets only
        </Checkbox>
        <Button variant="outline" onClick={() => (failNext.current = true)}>
          Fail the next read
        </Button>
      </div>
      <p id="listview-remote-label" className="salmon-field-label" style={{ margin: 0 }}>
        Tickets (2,000 on the server)
      </p>
      <Listbox<Ticket>
        key={openOnly ? 'open' : 'all'}
        aria-labelledby="listview-remote-label"
        data={tickets}
        query={openOnly ? OPEN_ONLY : ALL}
        getItemValue={ticketId}
        virtualization
        maxVisibleItems={7}
        value={value}
        onValueChange={(v) => setValue(v)}
        renderLoading={() => <Spinner size="sm" label="Loading tickets" />}
        renderError={({ error, retry }) => (
          <span style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}>
            {error instanceof Error ? error.message : 'Failed to load'}
            <Button onClick={retry}>
              Retry
            </Button>
          </span>
        )}
        onLoadError={(error) => push(`onLoadError: ${error instanceof Error ? error.message : String(error)}`)}
      />
      <p style={{ margin: 0 }}>
        Selected: <output>{value === null ? 'none' : `#${String(value)}`}</output>
      </p>
      <EventLog entries={log} label="Remote reads" />
    </div>
  );
}
```

The Listbox keyboard model, selection events and every other prop are on
the [Listbox](https://salmonui.dev/docs/dropdowns/listbox) page.

### Not included

These behaviors are left to the application on purpose, because the data
belongs to the application and React owns the lifecycle.

**Hiding items.** Pass a filtered array:
`data={items.filter((item) => item.visible)}`.

**Adding, removing and finding items.** There are no item
mutation methods. Keep items in state, update them with `setItems(...)`,
and look items up in that array.

**Header.** There is no built-in header. Render a heading and
connect it:

```tsx
<h2 id="contacts">Contacts</h2>
<Listbox aria-labelledby="contacts" data={contacts} />
```

**Sorting.** There is no sort option; sort once where the data
lives: `data.toSorted(byName)`, or `query={{ sorting: [{ columnId: 'name',
direction: 'asc' }] }}` on a remote source.

**Nested lists.** Drill-down navigation through child lists is a
mobile navigation pattern rather than a list behavior. Use
[TreeView](https://salmonui.dev/docs/navigation/tree-view) for hierarchical selection, or keep a
`path` state, render the current level in a `Listbox`, and add your own back
button.

**Nested-list animation.** With no nested navigation, there is no
slide animation to configure.

**Item height refresh.** The virtual list uses one fixed item
height, so there is no per-item height to refresh. Set
`virtualization={false}` for lists whose items differ in height.

**HTML encoding.** Content is `ReactNode` and HTML strings are
never parsed, so there is nothing to encode or sanitize. Write JSX in
`renderItem`.

**Persistence.** There is no built-in persistence: `localStorage`
is not readable on the server, so a persisted selection would cause a
hydration mismatch. Save `value` in `onValueChange` and pass it back as a
controlled prop.

**Lifecycle.** A React component unmounts with the tree, so there
is no destroy method: use conditional rendering, and put setup code in an
effect or a ref callback.

API reference: [`@salmonui/layout/list`](https://salmonui.dev/docs/reference/layout/list) and
[`@salmonui/dropdowns/listbox`](https://salmonui.dev/docs/reference/dropdowns/listbox).

The JavaScript is 0.30 KB gzip and the stylesheet 0.32 KB.
