# Combo box

Type to filter a long list and pick one or several items, with load-more and app-side results.

- Family: selection
- Import: `import { ComboBox } from "@senvenli/react/selection";`
- Page: https://design.senvenli.com/docs/components/combobox
- JSON: https://design.senvenli.com/docs/components/combobox.json

## Example: Pick one from a long list

Type to filter; the second line is searched too.

```tsx
import { ComboBox } from "@senvenli/react/selection";

const CUSTOMERS = [
  { id: "ada", label: "Ada Lovelace", description: "ada@example.com" },
  { id: "alan", label: "Alan Turing", description: "alan@example.com" },
  { id: "grace", label: "Grace Hopper", description: "grace@example.com" },
  { id: "katherine", label: "Katherine Johnson", description: "katherine@example.com" },
  { id: "linus", label: "Linus Torvalds", description: "linus@example.com" },
  { id: "margaret", label: "Margaret Hamilton", description: "margaret@example.com" },
];

export default function Example() {
  return (
    <div className="max-w-80">
      <ComboBox label="Customer" placeholder="Name or email" items={CUSTOMERS} defaultSelectedKey="ada" />
    </div>
  );
}
```

## Examples

### Several items

Chosen items become removable tags in the field.

```tsx
import { ComboBox } from "@senvenli/react/selection";

const MEMBERS = [
  { id: "ada", label: "Ada Lovelace", description: "Engineering" },
  { id: "alan", label: "Alan Turing", description: "Engineering" },
  { id: "grace", label: "Grace Hopper", description: "Operations" },
  { id: "katherine", label: "Katherine Johnson", description: "Finance" },
  { id: "margaret", label: "Margaret Hamilton", description: "Product", isDisabled: true },
];

export default function Example() {
  return (
    <div className="max-w-96">
      <ComboBox
        label="Reviewers"
        description="Margaret is on leave this week."
        selectionMode="multiple"
        menuTrigger="focus"
        items={MEMBERS}
        defaultSelectedKeys={["ada", "grace"]}
      />
    </div>
  );
}
```

### Create a missing item

A create row appears when nothing matches the text exactly.

```tsx
import { ComboBox, type ComboBoxItem } from "@senvenli/react/selection";
import { useState } from "react";

export default function Example() {
  const [labels, setLabels] = useState<ComboBoxItem[]>([
    { id: "bug", label: "Bug" },
    { id: "billing", label: "Billing" },
    { id: "feature", label: "Feature request" },
  ]);
  const [label, setLabel] = useState<string | number | null>(null);
  return (
    <div className="max-w-80">
      <ComboBox
        label="Label"
        placeholder="Find or create a label"
        items={labels}
        selectedKey={label ?? undefined}
        onSelectionChange={setLabel}
        createLabel={(text) => `Create “${text}”`}
        onCreate={(text) => {
          setLabels((current) => [...current, { id: text, label: text }]);
          setLabel(text);
        }}
      />
    </div>
  );
}
```

### Loaded from the server

A loadItems function fetches matches as people type and pages by cursor.

```tsx
import { ComboBox, type ComboBoxLoader } from "@senvenli/react/selection";

const PAGE = 5;
const ORDERS = Array.from({ length: 40 }, (_, index) => {
  const number = 1040 - index;
  return { id: `ORD-${number}`, label: `ORD-${number}`, description: index % 3 === 0 ? "Northwind Traders" : "Acme Supplies" };
});

// Stands in for `fetch("/api/orders?q=…&cursor=…", { signal })`.
const loadOrders: ComboBoxLoader = async (filterText, cursor) => {
  await new Promise((resolve) => setTimeout(resolve, 400));
  const query = filterText.toLowerCase();
  const matches = ORDERS.filter((order) => `${order.label} ${order.description}`.toLowerCase().includes(query));
  const start = Number(cursor ?? 0);
  const next = start + PAGE;
  return { items: matches.slice(start, next), cursor: next < matches.length ? String(next) : undefined };
};

export default function Example() {
  return (
    <div className="max-w-80">
      <ComboBox label="Order" placeholder="Order number or customer" menuTrigger="focus" loadItems={loadOrders} />
    </div>
  );
}
```

## Guidelines

### When to use it

- Picking from a long list (customers, products, countries) by typing.

### Use something else when

- [select](https://design.senvenli.com/docs/components/select.md): The list is short.
- [command](https://design.senvenli.com/docs/components/command.md): People search across actions and records with ⌘K, not fill a field.

## Accessibility

Keyboard:

- Arrow down: Opens the list.
- Enter: Picks the focused option.

Built in:

- Announces the result count and "No results".
- Matches ignore case and accents.
- Required fields show "Fill in this field." after a blur or a submit; your own `errorMessage` replaces it.

You provide:

- A visible label.

## API reference

### ComboBox

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| label | `React.ReactNode` |  | no | The label sits above the field. |
| items | `readonly ComboBoxItem[]` |  | no | The whole list, filtered here as the user types. |
| loadItems | `ComboBoxLoader` |  | no | Or load matches from the server (with paging when it returns a cursor). |
| description | `React.ReactNode` |  | no |  |
| errorMessage | `React.ReactNode` |  | no |  |
| placeholder | `string` |  | no |  |
| isRequired | `boolean` |  | no |  |
| requiredValidation | `RequiredValidation` |  | no | Who says an empty required ComboBox is missing: `field` (default) shows "Fill in this field." on blur and on a DS Form submit, which it then blocks; `app` only marks the field. Empty is no chosen item (multiple: no tag); with `allowsCustomValue`, typed text counts as a value. See {@link RequiredValidation}. The app's `isInvalid` (`true` with its `errorMessage`, or `false`) overrides the check, as on TextField. Disabled, empty and required, it still blocks a DS Form's submit and cannot take focus (as TextField). |
| isDisabled | `boolean` |  | no |  |
| isInvalid | `boolean` |  | no |  |
| name | `string` |  | no |  |
| menuTrigger | `"focus" \| "input"` |  | no | `input` (default) opens on typing; `focus` also on focus. The chevron always opens the full list. |
| emptyState | `React.ReactNode \| ((query: string) => React.ReactNode)` |  | no | The empty result: a node, or a function of the typed text for a message that quotes it. Defaults to "No results for “{query}”." in the provider locale. |
| onCreate | `(text: string) => void` |  | no | Adds a create row for the typed text when nothing matches it exactly. |
| createLabel | `(text: string) => string` |  | no | The create row's text; defaults to "Add “{query}”". |
| onInputChange | `(text: string) => void` |  | no | The typed text, for consumers that need it (custom values, analytics). |
| size | `FieldSize` |  | no |  |
| isLoading | `boolean` |  | no | The app is fetching items itself (with `items`, not `loadItems`): a spinner shows in the field and at the end of the list, and the change is announced. Items already shown stay selectable by keyboard and pointer. Together with `loadItems`, the field's own loading status is the one announced, so there is a single status region. |
| loadingText | `string` |  | no | What is announced and shown while loading; defaults to "Loading…" in the provider locale. |
| onSearchChange | `(search: string) => void` |  | no | The app searches on the server itself (with `items`, not `loadItems`;): told the text to search for, the typed text, or `""` when the list opens in full (the chevron, focus with `menuTrigger="focus"`) or the field just shows the chosen item's label. Debounce it on the app side. With it, `items` are the app's results and are shown as given, not filtered again here; the match in each row is still in bold. Not called on mount. The field hides rows found for another text itself: from the moment the text changes until the app's answer arrives, the list shows its loading row, the field its spinner, and the loading is announced politely, whatever the app does while it debounces. The answer has arrived when the rows change (ids, labels, second lines), when `isLoading` is set and cleared again (also for a server that finds the same rows), or, if neither, once the same rows have stood for a second with no new render. Nothing is asked of the app for it; `isLoading` is still the way to say a fetch is running. It is for a search that answers later. Filtering the rows the app already holds, synchronously, is the local filter's job (pass `items` without `onSearchChange`): here an answer with the very same rows and no `isLoading` stays hidden for that second. The field tells answers apart by when they arrive, not by the text they were asked for: an earlier request that answers after the next keystroke counts as the answer to the newer text. Abort superseded requests, or keep each answer under its own text (react-query's query key, without `placeholderData`). |
| onLoadMore | `() => void` |  | no | The next page of the app's own `items`, for an app that pages with its own query (react-query's infinite query): called when the list is scrolled near its end. Pass it only while there is another page (`hasNextPage ? fetchNextPage : undefined`), and set `isLoading` while the page loads: the list then ends in a loading row, the field shows its spinner and the loading is announced (politely). It is not called again while `isLoading` is set, nor twice before the app answers (a new page, `isLoading`, or a new search). The app's error stays the app's (`errorMessage`, `description`); after it, a scroll to the end asks again. With `loadItems`, which pages by itself, it is not used. |
| id | `string` |  | no | The input's id, so a label outside the component (`<label htmlFor={id}>`, an app's form field) names it. With neither `label` nor `aria-label`, that external label is the field's name and no label of its own renders. |
| aria-describedby | `string` |  | no | Ids of text outside the component that describes the input (an app's hint or error), added to its own. |
| aria-invalid | `boolean \| "true" \| "false"` |  | no | Set by a form row that owns the error text (the shared `Field` hands its control `aria-invalid`): the field shows its invalid state as with `isInvalid`, and without an `errorMessage` of its own draws no error row, so the row's message is the only one. It marks the input for assistive tech and draws it invalid only: unlike `isInvalid` it never becomes the input's native validity (React Aria's default outside a DS Form), so it never blocks a form's submit. |
| selectionMode | `"single" \| "multiple"` |  | no |  |
| selectedKey | `Key` |  | no | Controlled; may start undefined and become set later (never flips control). |
| defaultSelectedKey | `Key` |  | no |  |
| onSelectionChange | `(key: Key \| null) => void \| (keys: Key[]) => void` |  | no |  |
| selectedItem | `ComboBoxItem` |  | no | The chosen item when it is not on the loaded page (server search), so its label still shows. |
| allowsCustomValue | `boolean` |  | no | Typed text that matches no item is kept as the field's text; the key becomes `null` and `onInputChange` reports the text. |
| radius | `ComponentRadius` |  | no | Corner radius: `none`, `small`, `medium` (the design), `large` or `full`. The provider's default otherwise. |
| aria-label | `string` |  | no | Names the field for assistive technology when no visible label is shown. |
| selectedKeys | `readonly Key[]` |  | no |  |
| defaultSelectedKeys | `readonly Key[]` |  | no |  |
| selectedItems | `readonly ComboBoxItem[]` |  | no | Chosen items that are not on the loaded page, so their tags show their labels. |

### Tokens it reads

`--ds-background-brand-bold`, `--ds-background-disabled`, `--ds-background-input`, `--ds-background-input-hovered`, `--ds-background-neutral`, `--ds-background-neutral-pressed`, `--ds-background-neutral-subtle-hovered`, `--ds-background-selected`, `--ds-background-selected-hovered`, `--ds-border`, `--ds-border-bold`, `--ds-border-danger`, `--ds-border-focused`, `--ds-border-selected`, `--ds-easing-standard`, `--ds-icon-subtle`, `--ds-link`, `--ds-radius-control-medium`, `--ds-radius-control-small`, `--ds-radius-full`, `--ds-radius-large`, `--ds-radius-medium`, `--ds-radius-small`, `--ds-radius-xsmall`, `--ds-shadow-overlay`, `--ds-shadow-raised`, `--ds-size-control`, `--ds-size-control-compact`, `--ds-size-icon`, `--ds-space-050`, `--ds-space-075`, `--ds-space-100`, `--ds-space-150`, `--ds-space-200`, `--ds-surface-overlay`, `--ds-surface-raised`, `--ds-text`, `--ds-text-disabled`, `--ds-text-on-brand`, `--ds-text-subtle`, `--ds-text-subtlest`

## Related

- [select](https://design.senvenli.com/docs/components/select.md)
- [autocomplete](https://design.senvenli.com/docs/components/autocomplete.md)
