Skip to content

The open alternative to Salesforce, designed for AI.

16.5 KB
Raw Blame
---
title: Autocomplete
description: Suggest values while the user types and keeps focus in the input.
---

import { PageBanner } from "/snippets/page-banner.mdx"

import { StoryEmbed } from '/snippets/ui/StoryEmbed.mdx';
import AutocompleteReference from '/snippets/ui/generated/input/autocomplete.mdx';

## Overview

Use `Autocomplete` for suggestions attached to a text input. The input keeps its caret and keyboard focus while arrow keys highlight suggestions. Use [Select](/ui/primitives/input/select) when the user must choose a value from a fixed list. [Dropdown](/ui/components/navigation/dropdown) remains the higher-level component for menus and pickers.

<StoryEmbed
  storyId="ui-input-autocomplete--display"
  title="Autocomplete example"
  height={360}
/>

## Usage

Pass `items` to `Root` and render them through `List` so filtering updates the visible suggestions. `autoHighlight="always"` highlights the first result whenever the list opens.

```tsx
import { Autocomplete } from 'twenty-ui/primitives/input';

const FRUITS = ['Apple', 'Banana', 'Cherry'];

export const FruitInput = () => (
  <Autocomplete.Root items={FRUITS} autoHighlight="always">
    <Autocomplete.InputGroup>
      <Autocomplete.Input aria-label="Fruit" placeholder="Search fruits" />
    </Autocomplete.InputGroup>
    <Autocomplete.Portal>
      <Autocomplete.Positioner>
        <Autocomplete.Popup>
          <Autocomplete.Empty>No fruits found</Autocomplete.Empty>
          <Autocomplete.List>
            {(fruit: string) => (
              <Autocomplete.Item key={fruit} value={fruit}>
                {fruit}
              </Autocomplete.Item>
            )}
          </Autocomplete.List>
        </Autocomplete.Popup>
      </Autocomplete.Positioner>
    </Autocomplete.Portal>
  </Autocomplete.Root>
);
```

`value` and `onValueChange` control the input text. Use `defaultValue` for an uncontrolled initial value. Open state is independent: use `open` and `onOpenChange`, or `defaultOpen`. `Item.onClick` handles both pointer selection and Enter from the input.

`mode="list"` filters without changing input text on highlight. `mode="both"` also supplies inline completion. `mode="inline"` keeps all items and supplies inline completion; `mode="none"` keeps all items without inline completion. `readOnly` prevents inline completion from changing the input.

## Anatomy

Keep related parts inside a mounted `Autocomplete.Root`. Compose the portal destination, positioning wrapper, and content separately. `InputGroup` optionally groups the input with adjacent controls and anchors the popup to that group.

```text
Autocomplete.Root
├── Autocomplete.InputGroup (optional)
│   ├── Autocomplete.Input
│   ├── Autocomplete.Clear (optional)
│   └── Autocomplete.Trigger (optional)
│       └── Autocomplete.Icon (optional)
├── Autocomplete.Portal
│   ├── Autocomplete.Backdrop (optional)
│   └── Autocomplete.Positioner
│       └── Autocomplete.Popup
│           ├── Autocomplete.Arrow (optional)
│           ├── Autocomplete.Empty
│           └── Autocomplete.List
│               ├── Autocomplete.Item
│               ├── Autocomplete.Group (optional)
│               │   ├── Autocomplete.GroupLabel
│               │   └── Autocomplete.Collection
│               │       └── Autocomplete.Item
│               ├── Autocomplete.Row (optional, with Root.grid)
│               │   └── Autocomplete.Item
│               └── Autocomplete.Separator (optional)
├── Autocomplete.Status (optional)
└── Autocomplete.Value (optional)
```

| Part         | Purpose and native target                                                       |
| ------------ | ------------------------------------------------------------------------------- |
| `Root`       | Owns input value, filtering, highlights, and open state. Renders no element.    |
| `Value`      | Reads the input text through children or a render function. Renders no element. |
| `InputGroup` | Groups the input and adjacent controls. Targets a div.                          |
| `Input`      | Renders the combobox input and retains keyboard focus. Targets an input.        |
| `Trigger`    | Opens or closes suggestions. Targets a button.                                  |
| `Icon`       | Contains a trigger indicator. Targets a span.                                   |
| `Clear`      | Clears the input value. Targets a button.                                       |
| `Portal`     | Chooses the destination and mounting policy. Targets its portal div.            |
| `Backdrop`   | Supplies an optional overlay beneath the popup. Targets a div.                  |
| `Positioner` | Owns anchor, alignment, offsets, and collision handling. Targets its div.       |
| `Popup`      | Renders the suggestion content and optional focus behavior. Targets its div.    |
| `Arrow`      | Supplies an optional positioned arrow inside Popup. Targets a div.              |
| `List`       | Renders filtered items. Targets a div with the listbox or grid role.            |
| `Item`       | Renders a suggestion and handles pointer or keyboard selection. Targets a div.  |
| `Group`      | Groups related items. Targets a div.                                            |
| `GroupLabel` | Labels its parent group. Targets a div.                                         |
| `Row`        | Groups a row of items when `Root.grid` is enabled. Targets a div.               |
| `Collection` | Renders filtered items through a function child. Renders no element.            |
| `Separator`  | Separates items or groups visually. Targets a div.                              |
| `Empty`      | Announces when no matching items are available. Targets a div.                  |
| `Status`     | Announces changes such as asynchronous loading status. Targets a div.           |

Rendered parts retain native attributes, handlers, refs, state-based `className` and `style`, and element/function `render` composition from the installed Base UI API. Native props and refs target the part's own element. Custom components must forward supplied props and refs. Public part props and state types are exported from `twenty-ui/primitives/input`, together with Root actions and change/highlight event detail types.

`Autocomplete.useFilter()` supplies locale-aware `contains`, `startsWith`, and `endsWith` matching. `Autocomplete.useFilteredItems<TItem>()` reads the internally filtered collection under Root. Treat that result as read-only.

## Object and grouped items

Items can be strings or arbitrary objects. Use `itemToStringValue` to supply the text used for filtering, completion, and form submission. Objects shaped as `{ value, label }` use their label automatically. Render the same item value supplied through Root; no Twenty-specific item shape or selection equality prop is required. Autocomplete owns text input rather than a separate selected object value.

For grouped data, pass groups with an `items` array. Root preserves the item type for `itemToStringValue` and `onItemHighlighted`. Render each group's filtered children through `Group` and `Collection`:

```tsx
import { Autocomplete } from 'twenty-ui/primitives/input';
import { Text } from 'twenty-ui/primitives/typography';

type City = { id: number; name: string; country: string };
type CityGroup = { label: string; items: City[] };

const CITY_GROUPS: CityGroup[] = [
  {
    label: 'Europe',
    items: [
      { id: 1, name: 'Paris', country: 'France' },
      { id: 2, name: 'Lisbon', country: 'Portugal' },
    ],
  },
];

export const GroupedCityInput = () => (
  <Text
    style={{ display: 'grid', alignContent: 'start', gap: 8, width: '100%' }}
  >
    <label htmlFor="grouped-city">
      <Text render={<span />}>City</Text>
    </label>
    <Autocomplete.Root
      items={CITY_GROUPS}
      itemToStringValue={(city) => city.name}
      autoHighlight="always"
    >
      <Autocomplete.Input id="grouped-city" placeholder="Search cities" />
      <Autocomplete.Portal>
        <Autocomplete.Positioner>
          <Autocomplete.Popup>
            <Autocomplete.Empty>No matching cities</Autocomplete.Empty>
            <Autocomplete.List>
              {(group: CityGroup) => (
                <Autocomplete.Group key={group.label} items={group.items}>
                  <Autocomplete.GroupLabel>
                    {group.label}
                  </Autocomplete.GroupLabel>
                  <Autocomplete.Collection>
                    {(city: City) => (
                      <Autocomplete.Item
                        key={city.id}
                        value={city}
                        description={city.country}
                      >
                        {city.name}
                      </Autocomplete.Item>
                    )}
                  </Autocomplete.Collection>
                </Autocomplete.Group>
              )}
            </Autocomplete.List>
          </Autocomplete.Popup>
        </Autocomplete.Positioner>
      </Autocomplete.Portal>
    </Autocomplete.Root>
  </Text>
);
```

<StoryEmbed
  storyId="ui-input-autocomplete-collections--grouped-objects"
  title="Grouped object suggestions"
  height={440}
/>

`Item.startIcon`, `Item.endIcon`, and `Item.description` provide supporting content. Compose `Trigger` and `Clear` with Twenty UI [Button](/ui/primitives/input/button) through `render`. `Icon` can contain an icon from `twenty-ui/icon`. Keep `Status` and `Empty` mounted while updating their children so screen readers can announce changes.

## External filtering and server suggestions

Use `filteredItems` when your application owns filtering. It must preserve the flat or grouped structure of `items`. `filter` accepts a custom matching function; `filter={null}` disables internal filtering for results already filtered by a server.

```tsx
import { useState } from 'react';
import { Autocomplete } from 'twenty-ui/primitives/input';

const CITIES = ['Paris', 'London', 'Lisbon'];

export const CityPrefixInput = () => {
  const [value, setValue] = useState('');
  const { startsWith } = Autocomplete.useFilter();
  const filteredItems = CITIES.filter((city) => startsWith(city, value));

  return (
    <Autocomplete.Root
      items={CITIES}
      filteredItems={filteredItems}
      value={value}
      onValueChange={setValue}
      autoHighlight="always"
    >
      <Autocomplete.Input aria-label="City prefix" />
      <Autocomplete.Portal>
        <Autocomplete.Positioner>
          <Autocomplete.Popup>
            <Autocomplete.Empty>No matching cities</Autocomplete.Empty>
            <Autocomplete.List>
              {(city: string) => (
                <Autocomplete.Item key={city} value={city}>
                  {city}
                </Autocomplete.Item>
              )}
            </Autocomplete.List>
          </Autocomplete.Popup>
        </Autocomplete.Positioner>
      </Autocomplete.Portal>
    </Autocomplete.Root>
  );
};
```

Keep Root mounted when results arrive asynchronously. Control `open` independently so a response can open suggestions while the input remains focused. A mounted `Status` can announce loading; update `Empty` when the completed response has no results. The parent owns debounce, request cancellation, and stale response protection.

`onValueChange` and `onOpenChange` receive the upstream event details, including `reason`, native `event`, `trigger`, `cancel()`, and `allowPropagation()`. Controlled callers decide which requested updates to commit. For example, ignore the `escape-key` value change to keep a server query, or ignore `input-change` opening until results arrive. `onItemHighlighted` receives the original typed item and its highlight reason. Cancellation keeps the installed Base UI semantics; it does not replace the application's controlled-state policy.

## Input composition and native forms

`Input` accepts `size="sm"` or `size="md"` and uses the same styles as [Input](/ui/primitives/input/input). Compose it with an existing input using `render`. The composed control then owns its look: `Input` adds no Input styles and ignores `size`, but still passes your `className`, native attributes, handlers, ref, and state attributes. Forward them to the actual input element. Render Twenty UI `Input` to keep the standard look.

`InputGroup` provides layout and an anchor without adding input borders. It can contain chips or render an existing wrapper. Use [InputGroup](/ui/primitives/input/input-group) through its `render` prop when the whole group needs input styling, as the grouped object suggestions story does. An `Input` without `render` inside it drops its own border. Give the input an accessible label or compose it with [Field](/ui/primitives/input/field).

Root preserves the upstream `name`, `form`, `disabled`, `readOnly`, and native form behavior. Input's native attributes and ref target its input. `submitOnItemClick` opts into form submission when selecting a suggestion; the default does not submit.

Input preserves Base UI's native IME handling, including composition events and its keyboard confirmation guard.

The installed Base UI version retains an uncontrolled query on native form reset. For a controlled query, handle the form's `onReset` and restore the application's initial value.

## Placement, portal destination, and dismissal

`Positioner` defaults to `side="bottom"`, `align="start"`, and `sideOffset={8}`. It retains the installed Base UI anchor and positioning contract, including element/ref/function/virtual anchors, functional offsets, `positionMethod`, `collisionBoundary`, `collisionPadding`, `collisionAvoidance`, `arrowPadding`, `sticky`, and `disableAnchorTracking`. Configure these on Positioner. DirectionProvider controls logical placement and DOM direction.

`Popup` uses the anchor width as its minimum width. Set its `width` to supply a fixed content width. Its native props, styles, render composition, and ref target the content element independently of Positioner and Portal. Popup's `initialFocus` and `finalFocus` retain upstream focus options. By default, suggestions keep focus in the input.

Configure `container` and `keepMounted` on `Portal`. Omitting the container uses the nearest scoped ThemeProvider destination, then Base UI's parent portal or document body. An explicit `null` waits without rendering until a container is supplied. Element, ShadowRoot, and ref destinations pass through to Base UI. An unresolved ref retains Base UI's parent-portal/body fallback.

The default scoped destination preserves its CSS tokens and color scheme. An explicit destination inherits CSS from its actual DOM scope, so place it inside the intended theme scope or supply those styles there. React context and direction remain available across portals. ShadowRoot targets need the library's CSS and theme styles in that shadow tree.

Arrow keys change the highlighted item while the input keeps focus. Enter selects it; Escape and outside interaction request dismissal using upstream semantics. An outside press can activate the destination control. Higher-level pickers can own a different activation policy in their adapter. Call `event.preventBaseUIHandler()` in Input's `onKeyDown` to skip the built-in handler for a key you handle yourself. Use `event.preventDefault()` as well when suppressing the browser's native action.

`Root.inline` with `open` renders suggestions without the popup assembly. Inline items retain their `onClick` selection callbacks, but the installed upstream component fills the input automatically only when its Popup is present. Handle `Item.onClick` when inline selection should update your controlled text. `Root.grid` and `Row` support grid navigation. These modes retain the upstream collection and rendering APIs.

## Migration

Wrap Popup with `Autocomplete.Positioner` and `Autocomplete.Portal`. Positioner requires the Portal context; inline suggestions omit the whole popup assembly. Move placement, anchor, and collision props from Popup to Positioner. Move `container` and mounting configuration to Portal. Keep width, content styles, native props, handlers, and refs on Popup. Use an explicit `Arrow` child for an arrow.

Inside front components, keep the existing scoped portal policy. This API does not expand renderer portal destinations or geometry, scrolling, and dismissal capabilities; those renderer capabilities have separate ownership. Production picker adapters retain their deliberate activation workflows.

## Props

The reference is generated from the public component types. Native attributes, accessible names, and event handlers are also accepted on rendered parts.

<AutocompleteReference />

<PageBanner illustration="page-cover-input" />