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, and this page is available as Markdown at https://ifhover.github.io/leaf-ui/en/components/auto-complete.md.

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.

Input: EmptyLast selection: None
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>
  );
}

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.

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>
  );
}

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.

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>
  );
}

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.

Load failed
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>
  );
}

Disabled and read-only

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

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>
  );
}

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

PropertyTypeDefaultDescription
optionsreadonly (AutoCompleteOption|AutoCompleteOptionGroup)[]RequiredSuggestions in this group.
valuestring—Controlled text; the internal uncontrolled value is used when omitted.
defaultValuestring''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) => 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
disabledbooleanfalseDisable interaction.
readOnlybooleanfalseLock the value against typing, selection, clearing and removal.
allowClearboolean—Show a clear action.
filterOptionfalse | ((query: string, option: AutoCompleteOption) => boolean)Substring matchfalse disables local filtering; a function customizes matching
loadingboolean—Show a loading state.
errorContentReactNode—Content for loading errors and retry actions.
notFoundContentReactNode—Content when no options match.
optionRender(option: AutoCompleteOption) => ReactNode—Customize option content.
openboolean—Controlled open state.
defaultOpenbooleanfalseInitial open state for uncontrolled usage.
onOpenChange(open: boolean) => void—Called when the panel opens or closes.
virtualbooleanEnabled above 100 filtered suggestionsRender only visible suggestions; enabled by default above 100 filtered suggestions.
listHeightnumber248Maximum visible height of the suggestions panel.
optionHeightnumberTheme and density dependentEstimated virtual row height, calculated from the theme and density by default; actual rows are measured.
popupWidthnumber | string'trigger'Popup width; trigger matches the trigger, auto fits content (and may be narrower), numbers specify fixed pixels; CSS lengths are also supported.
popupMaxWidthnumber | string—Optional maximum popup width; no additional limit when unset, still bounded by the viewport.
popupPlacementPopupOptions['popupPlacement']—Placement relative to the trigger.
popupClassNamestring—Custom class for the popup.
popupStylePopupOptions['popupStyle']—Custom popup styles.
popupRenderPopupOptions['popupRender']—Wrap or extend popup content; retain the supplied content to preserve interaction.
getPopupContainerPopupOptions['getPopupContainer']—Return a popup container, including a ShadowRoot.
refRef<HTMLInputElement>—DOM reference

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

AutoCompleteOption

PropertyTypeDefaultDescription
valuestringRequiredUnique suggestion value; inserted into the input on selection.
labelReactNode—Visible suggestion label, also used by the default local filter.
searchLabelstring—Plain search text; defaults to a string label, otherwise value.
disabledbooleanfalseDisable the suggestion.

AutoCompleteOptionGroup

PropertyTypeDefaultDescription
labelReactNodeRequiredSuggestion group heading.
optionsreadonly AutoCompleteOption[]RequiredSuggestions in this group.