> Leaf UI 0.17.3 · Package: @ifhover/leaf-ui · Source: c3221834f84f2f48481a2054026b713456f8e5dc
> Browser documentation: https://ifhover.github.io/leaf-ui/en/components/auto-complete.html

> For AI agents: the complete documentation index is available at https://ifhover.github.io/leaf-ui/en/llms.txt, the full documentation bundle is available at https://ifhover.github.io/leaf-ui/en/llms-full.txt.

# AutoComplete

Suggest values while allowing free-text input.


## Basic usage

Suggestions use case-insensitive substring matching by default, without restricting free text. `onChange` responds to typing and selection; `onSelect` only responds to choosing a suggestion. An option with `disabled` cannot be selected.


Project name

Input: EmptyLast selection: None

basic.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/auto-complete/basic.tsx"
import { AutoComplete, Flex, Form, FormField, Text } from '@ifhover/leaf-ui';
import { useState } from 'react';

const options = [
  { value: 'Leaf Garden' },
  { value: 'Leaf Studio' },
  { value: 'Pine Forest' },
  { value: 'Archived Garden', disabled: true },
];

export function AutoCompleteBasic() {
  const [value, setValue] = useState('');
  const [selected, setSelected] = useState('');

  return (
    <Form layout="vertical">
      <FormField label="Project name">
        <AutoComplete
          aria-label="Project name"
          options={options}
          placeholder="Type Leaf or enter any text"
          value={value}
          onChange={setValue}
          onSelect={setSelected}
        />
      </FormField>
      <Flex direction="column" gap={8} role="status">
        <Text tone="muted">Input: {value || 'Empty'}</Text>
        <Text tone="muted">Last selection: {selected || 'None'}</Text>
      </Flex>
    </Form>
  );
}
```

Expand code

Focus or type to open suggestions. Use the arrow keys to highlight available options, Enter to select and Escape to close. Tab continues to the next control. Enter during IME composition does not select a suggestion.


## Examples

### Dynamic suggestions

`onSearch` receives typed text, and receives an empty string when cleared. It does not run on selection. When suggestions are generated by your application or returned by a server, set `filterOption={false}` to display them without local filtering.


Email address

search.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/auto-complete/search.tsx"
import { AutoComplete, type AutoCompleteOption, Form, FormField } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function AutoCompleteSearch() {
  const [options, setOptions] = useState<AutoCompleteOption[]>([]);

  return (
    <Form layout="vertical">
      <FormField label="Email address">
        <AutoComplete
          aria-label="Email address"
          placeholder="Enter an email prefix"
          options={options}
          allowClear
          filterOption={false}
          onSearch={(query) => {
            const prefix = query.split('@')[0] ?? '';
            setOptions(
              prefix
                ? ['gmail.com', 'outlook.com', 'icloud.com'].map((domain) => ({
                    value: `${prefix}@${domain}`,
                  }))
                : [],
            );
          }}
        />
      </FormField>
    </Form>
  );
}
```

Expand code

### Grouped suggestions

Use a group label and its `options` to organize suggestions. Provide `searchLabel` for rich labels. Selecting a suggestion inserts its `value`, not its visible `label`.


Team email

capabilities.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/auto-complete/capabilities.tsx"
import { AutoComplete, Flex, Form, FormField, Text } from '@ifhover/leaf-ui';

const options = [
  {
    label: 'Team',
    options: [
      {
        value: 'alice@example.com',
        label: (
          <Flex gap={8} align="center">
            <Text strong>Alice</Text>
            <Text tone="muted">Design</Text>
          </Flex>
        ),
        searchLabel: 'Alice Design',
      },
      {
        value: 'bob@example.com',
        label: (
          <Flex gap={8} align="center">
            <Text strong>Bob</Text>
            <Text tone="muted">Engineering</Text>
          </Flex>
        ),
        searchLabel: 'Bob Engineering',
      },
    ],
  },
];

export function Capabilities() {
  return (
    <Form layout="vertical">
      <FormField label="Team email">
        <AutoComplete
          aria-label="Team email"
          options={options}
          placeholder="Search a name or role"
        />
      </FormField>
    </Form>
  );
}
```

Expand code

### Loading and retry

This example simulates a failed load. Retrying performs an asynchronous local load and replaces the error with suggestions. For remote data, handle debouncing and response order in your application. When controlling `open`, update it in `onOpenChange`.


Remote project

Load failed

Simulate failure

loading.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/auto-complete/loading.tsx"
import { AutoComplete, type AutoCompleteOption, Button, Flex, Form, FormField, Text } from '@ifhover/leaf-ui';
import { useRef, useState } from 'react';

export function AutoCompleteLoading() {
  const [state, setState] = useState<'loading' | 'error' | 'ready'>('error');
  const [options, setOptions] = useState<AutoCompleteOption[]>([]);
  const [open, setOpen] = useState(false);
  const input = useRef<HTMLInputElement>(null);

  const retry = async () => {
    setState('loading');
    setOpen(true);
    input.current?.focus();
    await new Promise((resolve) => setTimeout(resolve, 800));
    setOptions([{ value: 'Leaf Garden' }, { value: 'Leaf Studio' }]);
    setState('ready');
  };

  return (
    <Form layout="vertical">
      <FormField label="Remote project">
        <AutoComplete
          ref={input}
          aria-label="Remote project"
          options={options}
          filterOption={false}
          open={open}
          onOpenChange={setOpen}
          loading={state === 'loading'}
          errorContent={
            state === 'error' ? (
              <Flex direction="column" align="start" gap={8}>
                <Text>Suggestions failed to load</Text>
                <Button onClick={retry} size="sm">
                  Retry
                </Button>
              </Flex>
            ) : undefined
          }
        />
      </FormField>
      <Text tone="muted" role="status">
        {state === 'loading'
          ? 'Loading'
          : state === 'error'
            ? 'Load failed'
            : 'Loaded 2 suggestions'}
      </Text>
      <Flex>
        <Button
          disabled={state === 'loading'}
          onClick={() => {
            setOptions([]);
            setState('error');
            setOpen(true);
          }}
        >
          Simulate failure
        </Button>
      </Flex>
    </Form>
  );
}
```

Expand code

### Disabled and read-only

`disabled` prevents interaction with the entire control. `readOnly` allows focus and copying but prevents editing, selection and clearing.


Disabled

Read only

states.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/auto-complete/states.tsx"
import { AutoComplete, Form, FormField } from '@ifhover/leaf-ui';

const options = [{ value: 'Leaf Garden' }, { value: 'Leaf Studio' }];

export function AutoCompleteStates() {
  return (
    <Form layout="vertical">
      <FormField label="Disabled">
        <AutoComplete aria-label="Disabled" options={options} defaultValue="Leaf Garden" disabled />
      </FormField>
      <FormField label="Read only">
        <AutoComplete
          aria-label="Read only"
          options={options}
          defaultValue="Leaf Garden"
          readOnly
        />
      </FormField>
    </Form>
  );
}
```

Expand code

Native input attributes such as `name`, `required` and `form` are supported. Uncontrolled fields follow native form reset; reset controlled values in application state. Application labels and options are not translated automatically.


## API

### AutoComplete API

| Property            | Type                                                                                                                  | Default                                | Description                                                                                                                                      |
| ------------------- | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `options`           | `readonly (`[`AutoCompleteOption`](#autocompleteoption)`\|`[`AutoCompleteOptionGroup`](#autocompleteoptiongroup)`)[]` | Required                               | Suggestions in this group.                                                                                                                       |
| `value`             | `string`                                                                                                              | —                                      | Controlled text; the internal uncontrolled value is used when omitted.                                                                           |
| `defaultValue`      | `string`                                                                                                              | `''`                                   | Initial text for uncontrolled usage; native form reset is supported.                                                                             |
| `onChange`          | `(value: string) => void`                                                                                             | —                                      | Return the full text after editing, clearing or selecting a suggestion.                                                                          |
| `onSelect`          | `(value: string, option: `[`AutoCompleteOption`](#autocompleteoption)`) => void`                                      | —                                      | Called only when a suggestion is selected, with its inserted value and option.                                                                   |
| `onSearch`          | `(query: string) => void`                                                                                             | —                                      | Return the query on user input, or an empty string on clearing; selecting a suggestion does not call it.                                         |
| `size`              | `'sm' \| 'md' \| 'lg'`                                                                                                | `'md'`                                 | Control size                                                                                                                                     |
| `status`            | `'error' \| 'warning'`                                                                                                | —                                      | Validation appearance                                                                                                                            |
| `disabled`          | `boolean`                                                                                                             | `false`                                | Disable interaction.                                                                                                                             |
| `readOnly`          | `boolean`                                                                                                             | `false`                                | Lock the value against typing, selection, clearing and removal.                                                                                  |
| `allowClear`        | `boolean`                                                                                                             | —                                      | Show a clear action.                                                                                                                             |
| `filterOption`      | `false \| ((query: string, option: `[`AutoCompleteOption`](#autocompleteoption)`) => boolean)`                        | Substring match                        | false disables local filtering; a function customizes matching                                                                                   |
| `loading`           | `boolean`                                                                                                             | —                                      | Show a loading state.                                                                                                                            |
| `errorContent`      | `ReactNode`                                                                                                           | —                                      | Content for loading errors and retry actions.                                                                                                    |
| `notFoundContent`   | `ReactNode`                                                                                                           | —                                      | Content when no options match.                                                                                                                   |
| `optionRender`      | `(option: `[`AutoCompleteOption`](#autocompleteoption)`) => ReactNode`                                                | —                                      | Customize option content.                                                                                                                        |
| `open`              | `boolean`                                                                                                             | —                                      | Controlled open state.                                                                                                                           |
| `defaultOpen`       | `boolean`                                                                                                             | `false`                                | Initial open state for uncontrolled usage.                                                                                                       |
| `onOpenChange`      | `(open: boolean) => void`                                                                                             | —                                      | Called when the panel opens or closes.                                                                                                           |
| `virtual`           | `boolean`                                                                                                             | Enabled above 100 filtered suggestions | Render only visible suggestions; enabled by default above 100 filtered suggestions.                                                              |
| `listHeight`        | `number`                                                                                                              | `248`                                  | Maximum visible height of the suggestions panel.                                                                                                 |
| `optionHeight`      | `number`                                                                                                              | Theme and density dependent            | Estimated virtual row height, calculated from the theme and density by default; actual rows are measured.                                        |
| `popupWidth`        | `number \| string`                                                                                                    | `'trigger'`                            | Popup width; trigger matches the trigger, auto fits content (and may be narrower), numbers specify fixed pixels; CSS lengths are also supported. |
| `popupMaxWidth`     | `number \| string`                                                                                                    | —                                      | Optional maximum popup width; no additional limit when unset, still bounded by the viewport.                                                     |
| `popupPlacement`    | [`PopupOptions`](https://ifhover.github.io/leaf-ui/en/api/popup-options.md#popupoptions)`['popupPlacement']`          | —                                      | Placement relative to the trigger.                                                                                                               |
| `popupClassName`    | `string`                                                                                                              | —                                      | Custom class for the popup.                                                                                                                      |
| `popupStyle`        | [`PopupOptions`](https://ifhover.github.io/leaf-ui/en/api/popup-options.md#popupoptions)`['popupStyle']`              | —                                      | Custom popup styles.                                                                                                                             |
| `popupRender`       | [`PopupOptions`](https://ifhover.github.io/leaf-ui/en/api/popup-options.md#popupoptions)`['popupRender']`             | —                                      | Wrap or extend popup content; retain the supplied content to preserve interaction.                                                               |
| `getPopupContainer` | [`PopupOptions`](https://ifhover.github.io/leaf-ui/en/api/popup-options.md#popupoptions)`['getPopupContainer']`       | —                                      | Return a popup container, including a ShadowRoot.                                                                                                |
| `ref`               | `Ref<HTMLInputElement>`                                                                                               | —                                      | DOM reference                                                                                                                                    |

`placeholder`, `name`, `required`, `form`, `maxLength` and `aria-*` are forwarded to the input. `className` and `style` apply to the outer container.

#### AutoCompleteOption

| Property      | Type        | Default  | Description                                                      |
| ------------- | ----------- | -------- | ---------------------------------------------------------------- |
| `value`       | `string`    | Required | Unique suggestion value; inserted into the input on selection.   |
| `label`       | `ReactNode` | —        | Visible suggestion label, also used by the default local filter. |
| `searchLabel` | `string`    | —        | Plain search text; defaults to a string label, otherwise value.  |
| `disabled`    | `boolean`   | `false`  | Disable the suggestion.                                          |

#### AutoCompleteOptionGroup

| Property  | Type                                                       | Default  | Description                |
| --------- | ---------------------------------------------------------- | -------- | -------------------------- |
| `label`   | `ReactNode`                                                | Required | Suggestion group heading.  |
| `options` | `readonly `[`AutoCompleteOption`](#autocompleteoption)`[]` | Required | Suggestions in this group. |
