> For the complete documentation index, see [llms.txt](https://docs.rierino.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.rierino.com/sdk-core-ui/components/autocomplete.md). Agents can also search and read this documentation through its [MCP server](https://docs.rierino.com/~gitbook/mcp).

# Autocomplete

Lets people pick one or more options from a list they can search, or type a value of their own.

{% code title="autocomplete/demo.tsx" %}

```tsx
import { useState } from "react";
import { AutocompleteInput } from "@rierino-open/core-ui";

const categories = [
  { label: "Shirts", value: "shirts" },
  { label: "Trousers", value: "trousers" },
  { label: "Jackets", value: "jackets" },
  { label: "Knitwear", value: "knitwear" },
  { label: "Shoes", value: "shoes" },
  { label: "Accessories", value: "accessories" },
];

export default function AutocompleteDemo() {
  const [category, setCategory] = useState<string[]>(["jackets"]);

  return (
    <div style={{ width: 320 }}>
      <AutocompleteInput
        name="category"
        placeholder="Pick a category"
        selectionMode="single"
        showInput
        options={categories}
        selectedItems={category}
        onChange={(selected) => setCategory(selected.map((o) => String(o.value)))}
      />
    </div>
  );
}
```

{% endcode %}

## Usage

{% tabs %}
{% tab title="React app" %}

```tsx
import { AutocompleteInput } from '@rierino-open/core-ui';

const [selected, setSelected] = useState<string[]>([]);

<AutocompleteInput
  name="category"
  placeholder="Pick a category"
  options={[
    { label: 'Shirts', value: 'shirts' },
    { label: 'Jackets', value: 'jackets' },
  ]}
  selectedItems={selected}
  onChange={(options) => setSelected(options.map((o) => String(o.value)))}
/>
```

{% endtab %}

{% tab title="Hosted editor" %}

```jsx
import React, { useState } from 'react';
import CoreUI from '@rierino-open/core-ui';
const { AutocompleteInput } = CoreUI;

const [selected, setSelected] = useState([]);

<AutocompleteInput
  name="category"
  placeholder="Pick a category"
  options={[
    { label: 'Shirts', value: 'shirts' },
    { label: 'Jackets', value: 'jackets' },
  ]}
  selectedItems={selected}
  onChange={(options) => setSelected(options.map((o) => String(o.value)))}
/>
```

{% endtab %}
{% endtabs %}

The field is always controlled, and its value and change event have different shapes:

* `selectedItems` is an **array of option values**, even in single mode: `['jackets']`, or `[]` for nothing.
* `onChange` receives the **selected options** as objects. Map them back to their values to update `selectedItems`.

`name`, `options`, `selectedItems` and `onChange` are required.

## Examples

### Working with the value

{% code title="autocomplete/value.tsx" %}

```tsx
import { useState } from "react";
import { AutocompleteInput } from "@rierino-open/core-ui";

const colours = [
  { label: "Navy", value: "navy" },
  { label: "Sand", value: "sand" },
  { label: "Olive", value: "olive" },
  { label: "Black", value: "black" },
];

export default function AutocompleteValue() {
  // selectedItems holds values; onChange hands you the selected options.
  const [values, setValues] = useState<string[]>(["navy"]);

  return (
    <div style={{ display: "grid", gap: 12, width: 320 }}>
      <AutocompleteInput
        name="colours"
        placeholder="Colours"
        options={colours}
        selectedItems={values}
        onChange={(selected) => setValues(selected.map((o) => String(o.value)))}
      />
      <code style={{ fontSize: 11 }}>selectedItems: {JSON.stringify(values)}</code>
    </div>
  );
}
```

{% endcode %}

A value in `selectedItems` that has no matching option is still shown, using the value itself as the label. `onChange` hands such a value back as `{ value, label: value }`.

### Single selection

`selectionMode="single"` keeps one value and closes the list once it is picked. Without `showInput`, the field works like a select: people can't type, and the selected label is shown as text. The field can be focused with `Tab` and opened with `↓`.

{% code title="autocomplete/single.tsx" %}

```tsx
import { useState } from "react";
import { AutocompleteInput } from "@rierino-open/core-ui";

const statuses = [
  { label: "Draft", value: "draft" },
  { label: "In review", value: "review" },
  { label: "Published", value: "published" },
  { label: "Archived", value: "archived" },
];

export default function AutocompleteSingle() {
  const [status, setStatus] = useState<string[]>(["draft"]);

  return (
    <div style={{ width: 320 }}>
      <AutocompleteInput
        name="status"
        selectionMode="single"
        options={statuses}
        selectedItems={status}
        onChange={(selected) => setStatus(selected.map((o) => String(o.value)))}
      />
    </div>
  );
}
```

{% endcode %}

### Searchable single selection

Add `showInput` to let people type to filter the list, as in the example at the top of the page. The input shows the selected option's label. When the field loses focus:

* text that matches an option's label or value (ignoring case) selects that option;
* empty text clears the value;
* any other text is cleared, unless [custom values](#custom-values) are allowed.

### Multiple selection

Multiple selection is the default. Selected options appear as tags in the order they were picked, and the list stays open so people can pick several. Picking a selected option again, or pressing a tag's ×, removes it.

{% code title="autocomplete/multiple.tsx" %}

```tsx
import { useState } from "react";
import { AutocompleteInput } from "@rierino-open/core-ui";

const channels = [
  { label: "Web store", value: "web" },
  { label: "Mobile app", value: "mobile" },
  { label: "Marketplace", value: "marketplace" },
  { label: "Retail stores", value: "retail" },
  { label: "Wholesale", value: "wholesale" },
];

export default function AutocompleteMultiple() {
  const [selected, setSelected] = useState<string[]>(["web", "mobile"]);

  return (
    <div style={{ width: 320 }}>
      <AutocompleteInput
        name="channels"
        placeholder="Sales channels"
        options={channels}
        selectedItems={selected}
        onChange={(options) => setSelected(options.map((o) => String(o.value)))}
      />
    </div>
  );
}
```

{% endcode %}

### Searching

Typing filters the options by label. The match ignores case and accents, and applies 400 ms after typing stops. `Enter` picks the first match. When nothing matches, the list shows `noResultsMessage`.

{% code title="autocomplete/no-results.tsx" %}

```tsx
import { useState } from "react";
import { AutocompleteInput } from "@rierino-open/core-ui";

const languages = [
  { label: "English", value: "en" },
  { label: "Türkçe", value: "tr" },
  { label: "Deutsch", value: "de" },
];

export default function AutocompleteNoResults() {
  const [languagesSelected, setLanguages] = useState<string[]>([]);

  return (
    <div style={{ width: 320 }}>
      <AutocompleteInput
        name="languages"
        placeholder="Type “fr” to see the message"
        noResultsMessage="No language matches your search"
        options={languages}
        selectedItems={languagesSelected}
        onChange={(options) => setLanguages(options.map((o) => String(o.value)))}
      />
    </div>
  );
}
```

{% endcode %}

### Server-side search

For long or remote lists, pass `onSearch`. It is called with the search text once typing stops, and the options are no longer filtered locally: fetch the matches and pass them as `options`.

{% code title="autocomplete/server-search.tsx" %}

```tsx
import { useState } from "react";
import { AutocompleteInput } from "@rierino-open/core-ui";

type Option = { label: string; value: string };

const catalogue: Option[] = Array.from({ length: 200 }, (_, i) => ({
  label: `Product ${String(i + 1).padStart(3, "0")}`,
  value: `prd-${i + 1}`,
}));

// Stands in for an API call.
function searchProducts(text: string): Promise<Option[]> {
  const matches = catalogue.filter((p) => p.label.toLowerCase().includes(text.toLowerCase()));
  return new Promise((resolve) => setTimeout(() => resolve(matches.slice(0, 10)), 300));
}

export default function AutocompleteServerSearch() {
  const [options, setOptions] = useState<Option[]>(catalogue.slice(0, 10));
  const [selected, setSelected] = useState<string[]>([]);

  return (
    <div style={{ width: 320 }}>
      <AutocompleteInput
        name="product"
        placeholder="Search 200 products"
        selectionMode="single"
        showInput
        options={options}
        selectedItems={selected}
        onSearch={async (text) => setOptions(await searchProducts(text ?? ""))}
        onChange={(picked) => setSelected(picked.map((o) => String(o.value)))}
      />
    </div>
  );
}
```

{% endcode %}

### Custom values

`allowsCustomValue` lets people use values that aren't in `options`:

* **Multiple:** the list ends with an "Add …" row for the typed text.
* **Single with `showInput`:** text that matches no option is kept as the value when the field loses focus.

{% code title="autocomplete/custom-values.tsx" %}

```tsx
import { useState } from "react";
import { AutocompleteInput } from "@rierino-open/core-ui";

const tags = [
  { label: "new", value: "new" },
  { label: "sale", value: "sale" },
  { label: "bestseller", value: "bestseller" },
];

const brands = [
  { label: "Northwind", value: "northwind" },
  { label: "Contoso", value: "contoso" },
];

export default function AutocompleteCustomValues() {
  const [selectedTags, setSelectedTags] = useState<string[]>(["new"]);
  const [brand, setBrand] = useState<string[]>([]);

  return (
    <div style={{ display: "grid", gap: 16, width: 320 }}>
      {/* Multiple: type a word and pick "Add …" to create a tag. */}
      <AutocompleteInput
        name="tags"
        placeholder="Tags"
        allowsCustomValue
        options={tags}
        selectedItems={selectedTags}
        onChange={(options) => setSelectedTags(options.map((o) => String(o.value)))}
      />

      {/* Single with an input: text that matches no option is kept when the field loses focus. */}
      <AutocompleteInput
        name="brand"
        placeholder="Brand"
        selectionMode="single"
        showInput
        allowsCustomValue
        options={brands}
        selectedItems={brand}
        onChange={(options) => setBrand(options.map((o) => String(o.value)))}
      />
    </div>
  );
}
```

{% endcode %}

### Groups

`groupBy` names an option property to group the list by. Each distinct value becomes a heading, in the order the groups first appear in `options`.

{% code title="autocomplete/groups.tsx" %}

```tsx
import { useState } from "react";
import { AutocompleteInput } from "@rierino-open/core-ui";

const warehouses = [
  { label: "Istanbul", value: "ist", region: "Europe" },
  { label: "Berlin", value: "ber", region: "Europe" },
  { label: "Lisbon", value: "lis", region: "Europe" },
  { label: "Dubai", value: "dxb", region: "Middle East" },
  { label: "Riyadh", value: "ruh", region: "Middle East" },
];

export default function AutocompleteGroups() {
  const [selected, setSelected] = useState<string[]>([]);

  return (
    <div style={{ width: 320 }}>
      <AutocompleteInput
        name="warehouses"
        placeholder="Warehouses"
        groupBy="region"
        options={warehouses}
        selectedItems={selected}
        onChange={(options) => setSelected(options.map((o) => String(o.value)))}
      />
    </div>
  );
}
```

{% endcode %}

### Icons and descriptions

An option's `icon` is shown before its label, and in single mode also next to the selected value. Its `description` appears in a tooltip when the option is hovered.

{% code title="autocomplete/icons.tsx" %}

```tsx
import { useState } from "react";
import { AutocompleteInput } from "@rierino-open/core-ui";
import { Globe, Smartphone, Store } from "lucide-react";

const channels = [
  {
    label: "Web store",
    value: "web",
    icon: <Globe size={14} />,
    description: "Orders placed on the website",
  },
  {
    label: "Mobile app",
    value: "mobile",
    icon: <Smartphone size={14} />,
    description: "Orders placed in the iOS and Android apps",
  },
  {
    label: "Retail stores",
    value: "retail",
    icon: <Store size={14} />,
    description: "Sales at the till in physical stores",
  },
];

export default function AutocompleteIcons() {
  const [channel, setChannel] = useState<string[]>(["web"]);

  return (
    <div style={{ width: 320 }}>
      <AutocompleteInput
        name="channel"
        selectionMode="single"
        options={channels}
        selectedItems={channel}
        onChange={(options) => setChannel(options.map((o) => String(o.value)))}
      />
    </div>
  );
}
```

{% endcode %}

### Disabled options

An option with `disabled: true` is dimmed and can't be clicked. A disabled option can also act as a placeholder in single mode: while it is selected, the field shows it greyed out.

{% code title="autocomplete/disabled-options.tsx" %}

```tsx
import { useState } from "react";
import { AutocompleteInput } from "@rierino-open/core-ui";

const sizes = [
  { label: "Select a size", value: "placeholder", disabled: true },
  { label: "S", value: "s" },
  { label: "M", value: "m" },
  { label: "L — out of stock", value: "l", disabled: true },
  { label: "XL", value: "xl" },
];

export default function AutocompleteDisabledOptions() {
  // A disabled option can act as a placeholder: it shows greyed out while it is selected.
  const [size, setSize] = useState<string[]>(["placeholder"]);

  return (
    <div style={{ width: 320 }}>
      <AutocompleteInput
        name="size"
        selectionMode="single"
        options={sizes}
        selectedItems={size}
        onChange={(options) => setSize(options.map((o) => String(o.value)))}
      />
    </div>
  );
}
```

{% endcode %}

### Option colours

`props.hoverBg` on an option sets its hover background, and its text turns white on hover. A selected option shows its label in that colour.

{% code title="autocomplete/colours.tsx" %}

```tsx
import { useState } from "react";
import { AutocompleteInput } from "@rierino-open/core-ui";

const priorities = [
  { label: "Low", value: "low", props: { hoverBg: "#259374" } },
  { label: "Medium", value: "medium", props: { hoverBg: "#FF7E47" } },
  { label: "High", value: "high", props: { hoverBg: "#EB475A" } },
];

export default function AutocompleteColours() {
  const [priority, setPriority] = useState<string[]>(["medium"]);

  return (
    <div style={{ width: 320 }}>
      <AutocompleteInput
        name="priority"
        selectionMode="single"
        options={priorities}
        selectedItems={priority}
        onChange={(options) => setPriority(options.map((o) => String(o.value)))}
      />
    </div>
  );
}
```

{% endcode %}

### Custom input text

In single mode with `showInput`, `renderInputValue` sets the text shown in the input for the selected option. Typing still filters the list by label.

{% code title="autocomplete/input-value.tsx" %}

```tsx
import { useState } from "react";
import { AutocompleteInput } from "@rierino-open/core-ui";

const products = [
  { label: "Linen shirt", value: "LS-2041", sku: "LS-2041" },
  { label: "Chino trousers", value: "CT-1188", sku: "CT-1188" },
  { label: "Wool coat", value: "WC-0907", sku: "WC-0907" },
];

export default function AutocompleteInputValue() {
  const [product, setProduct] = useState<string[]>(["LS-2041"]);

  return (
    <div style={{ width: 320 }}>
      <AutocompleteInput
        name="product"
        selectionMode="single"
        showInput
        options={products}
        selectedItems={product}
        renderInputValue={(option) => `${option.label} (${option.sku})`}
        onChange={(options) => setProduct(options.map((o) => String(o.value)))}
      />
    </div>
  );
}
```

{% endcode %}

### Custom option content

`AutocompleteBase` takes a render function as its child, so you can lay out each option yourself. Return an `Item` from `react-stately` (a dependency of Core UI) keyed by the option's value. Searching still matches the option's `label`.

{% code title="autocomplete/custom-items.tsx" %}

```tsx
import { useState } from "react";
import { AutocompleteBase } from "@rierino-open/core-ui";
import { Item } from "react-stately";

const people = [
  { label: "Ada Lovelace", value: "ada", email: "ada@example.com" },
  { label: "Alan Turing", value: "alan", email: "alan@example.com" },
  { label: "Grace Hopper", value: "grace", email: "grace@example.com" },
];

export default function AutocompleteCustomItems() {
  const [owners, setOwners] = useState<string[]>([]);

  return (
    <div style={{ width: 320 }}>
      <AutocompleteBase
        name="owners"
        placeholder="Owners"
        options={people}
        selectedItems={owners}
        onChange={(options) => setOwners(options.map((o) => String(o.value)))}
      >
        {(person) => (
          <Item key={person.value} textValue={person.label}>
            <span style={{ display: "grid", textAlign: "left" }}>
              <span>{person.label}</span>
              <span style={{ fontSize: 10, opacity: 0.7 }}>{person.email}</span>
            </span>
          </Item>
        )}
      </AutocompleteBase>
    </div>
  );
}
```

{% endcode %}

`AutocompleteBase` isn't usable in hosted editors, which can't import `react-stately`. Use `AutocompleteInput` there.

## Keyboard

| Key         | In the input                                              | In the list                                                     |
| ----------- | --------------------------------------------------------- | --------------------------------------------------------------- |
| `↓`         | Opens the list and moves to the first option              | Moves to the next option                                        |
| `↑`         |                                                           | Moves to the previous option; from the first, back to the input |
| `Enter`     | Picks the first match while searching                     | Picks the focused option                                        |
| `Esc`       | Closes the list                                           | Closes the list                                                 |
| `Backspace` | In an empty input, focuses the last tag; again removes it |                                                                 |
| `←` `→`     | In an empty input, moves between tags                     |                                                                 |

## Accessibility

* **There's no label prop yet.** AutocompleteInput doesn't accept `aria-label`, and the placeholder disappears once something is selected. Put a visible label next to the field, as in Rierino forms.
* The list is a listbox with options, navigable with the keyboard as above. Selected options are marked with a check icon as well as colour.
* An option's `description` is only available on hover. Don't put information there that people need to make a choice.

## Styling

| Target                    | How                                                                                                                                                                                     |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The field                 | `className`. Its border uses `--border-color`, and `--border-color-focus` while focused ([theme variables](https://docs.rierino.com/sdk-core-ui/foundations/colors.md#theme-variables)) |
| The list                  | `popoverClassName`. It is as wide as the field and scrolls beyond 288px                                                                                                                 |
| Tags and selected options | `--primary`                                                                                                                                                                             |
| Option hover              | `props.hoverBg` per option                                                                                                                                                              |
| The tags row              | The `Rie-tags-wrapper` class                                                                                                                                                            |

## API reference

### AutocompleteInput

| Prop                | Type                               | Default        | Description                                                                                                                                                                                      |
| ------------------- | ---------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `onChange`          | `AutocompleteInputOnChangeHandler` |                | **Required.** Called when the selection changes, with the selected **options** (not their values), in selection order. A value without a matching option is passed as `{ value, label: value }`. |
| `placeholder`       | `string`                           |                | Shown while nothing is selected.                                                                                                                                                                 |
| `allowsCustomValue` | `boolean`                          |                | Lets people add values that aren't in `options`. In multiple mode the list offers "Add …" for the typed text; in single mode with `showInput`, unmatched text is kept on blur.                   |
| `selectionMode`     | `SelectionMode`                    | `"multiple"`   | `multiple` shows the selection as removable tags. `single` keeps one value and closes the list once it is picked.                                                                                |
| `selectedItems`     | `string[]`                         |                | **Required.** The values of the selected options. The field is always controlled through this prop.                                                                                              |
| `options`           | `Option[]`                         |                | **Required.** The options to choose from.                                                                                                                                                        |
| `name`              | `string`                           |                | **Required.** The `name` of the text input.                                                                                                                                                      |
| `disabled`          | `boolean`                          |                | Disables typing in the input.                                                                                                                                                                    |
| `showInput`         | `boolean`                          |                | In single mode, shows a text input so people can type to search, and shows the selected label in it. Without it, single mode works like a select. Multiple mode always has an input.             |
| `noResultsMessage`  | `string`                           | `"No results"` | Shown in the list when the search matches no option.                                                                                                                                             |
| `className`         | `string`                           |                | Classes added to the field.                                                                                                                                                                      |
| `popoverClassName`  | `string`                           |                | Classes added to the dropdown list.                                                                                                                                                              |
| `groupBy`           | `string`                           |                | The name of an option property to group the list by, such as `"group"`.                                                                                                                          |
| `onBlur`            | `(() => void)`                     |                | Called when the list closes.                                                                                                                                                                     |
| `renderInputValue`  | `((T: Option) => string)`          |                | In single mode with `showInput`, the text shown in the input for the selected option.                                                                                                            |
| `onSearch`          | `((T: string \| null) => void)`    |                | Called with the search text, 400 ms after typing stops. When set, the options are not filtered locally: update `options` with the results yourself.                                              |

`AutocompleteBase` takes the same props, plus the render function as `children`.

### Option

| Prop          | Type               | Default | Description                                                                          |
| ------------- | ------------------ | ------- | ------------------------------------------------------------------------------------ |
| `icon`        | `React.ReactNode`  |         | Shown before the label in the list, and before the selection in single mode.         |
| `description` | `React.ReactNode`  |         | Shown in a tooltip when the option is hovered.                                       |
| `label`       | `string \| number` |         | **Required.** The text shown for the option, and what the search matches against.    |
| `value`       | `string \| number` |         | **Required.** The option's identifier. `selectedItems` holds these values.           |
| `props`       | `any`              |         | Extra settings. `hoverBg` sets the option's hover background (its text turns white). |
| `disabled`    | `boolean`          |         | Dims the option and ignores clicks on it.                                            |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.rierino.com/sdk-core-ui/components/autocomplete.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
