Skip to content
WunderUI

Autocomplete

Free

A text field that suggests matches as you type. The text stays yours: a suggestion fills the field, and any other text is kept too.

npx wunderui-cli add autocomplete

Playground

Installation

bash
npx wunderui-cli add autocomplete

Writes the source into your project with its dependencies and, on first use, the styles - see Installation.

Then import what you need:

tsx
import {
  Autocomplete,
  AutocompleteEmpty,
  AutocompleteInput,
  AutocompleteInputGroup,
  AutocompleteItem,
  AutocompleteList,
  AutocompletePopup,
  AutocompletePortal,
} from "@/components/ui/autocomplete"

Then use it:

tsx
import {
  Autocomplete,
  AutocompleteEmpty,
  AutocompleteInput,
  AutocompleteInputGroup,
  AutocompleteItem,
  AutocompleteList,
  AutocompletePopup,
} from "@/components/ui/autocomplete"

const cities = ["Berlin", "Copenhagen", "Lisbon", "Madrid", "Vienna"]

export function CityField() {
  return (
    <Autocomplete items={cities}>
      <AutocompleteInputGroup>
        <AutocompleteInput aria-label="City" placeholder="Search cities" />
      </AutocompleteInputGroup>
      <AutocompletePopup>
        <AutocompleteEmpty>No cities match.</AutocompleteEmpty>
        <AutocompleteList>
          {(city) => (
            <AutocompleteItem key={city} value={city}>
              {city}
            </AutocompleteItem>
          )}
        </AutocompleteList>
      </AutocompletePopup>
    </Autocomplete>
  )
}

Expected result: You should see a text field with the placeholder Search cities. Type li and the list keeps Berlin and Lisbon; press Arrow Down and Enter and the field fills with Berlin.

When to use

Use Autocomplete for

  • Free text with help, such as a city, a search term or a label that may be new
  • A field where any value is valid and the suggestions only save typing
  • Search boxes whose suggestions come from your own data

Use something else for

  • Combobox for the answer must be one of the entries
  • Select for a short, fixed list, with no typing
  • Dropdown Menu for a list of actions, not a value for a field

Content

A suggestion is a row you build: plain text, text with an icon, or a person with an avatar and a second line. Give the item an object as its value when it carries more than a label.

Matching

By default a suggestion matches when it contains what was typed, ignoring case and accents. Pass a filter to match from the start of a word, and auto highlight so Enter takes the first match.

States

Hover and focus are real states: point at the field or press Tab. An invalid field turns its border and ring red and says why under it, and a disabled field dims and ignores keyboard and pointer.

Keyboard interactions

The input is a native text field, so the browser provides focus, typing and the caret. The list is not in the tab order: arrow keys reach it from the input, and focus stays there.

TaborShiftTab
Moves focus into the field and out of it. Leaving closes the list and keeps the text.
A–Z
Typing opens the list and keeps the suggestions that match. Clearing the field closes it again.
ArrowDownorArrowUp
Opens the list if it is closed, then moves the highlight to the next or previous suggestion. At the end of the list focus goes back to the text with nothing highlighted, and one more press starts at the other end.
Enter
Takes the highlighted suggestion: it fills the field and closes the list. With nothing highlighted Enter does what it does in any text field, so a form around the field is submitted.
Escape
Closes the list. Pressed again, it clears the text.

Behavior and motion

What the field does with text, matching, the list and motion.

Text, not a choice
The value is the text in the field. Choosing a suggestion fills it with that text, text that matches nothing stays as typed, and you should check it on submit when only some values are valid.
Opening
The list opens when the person types or presses Arrow Down or Arrow Up, and closes when the field is empty. It can also open on click, and the field keeps focus while it is open.
Matching
A suggestion matches when it contains the typed text, ignoring case and accents. You can replace the rule, highlight the first match so Enter takes it, and cap the number of suggestions.
Objects as items
Items can be objects. Give each item the object as its value, and the root a function that turns it into the field's text.
No match
The empty line shows in the list when nothing matches and is hidden while it has no content. Give it a sentence so a list without matches never looks broken.
Position and size
The list opens below the field, 4 px away and as wide as the field (12 rem at least). It flips above when there is no room below and scrolls when it is taller than the room left.
Highlight
The pointer and the keyboard share one highlight, drawn with the page fill of a hovered row. Moving the pointer over a row highlights it; you can switch that off.
Invalid and disabled
Mark the input invalid to turn the border and focus ring red, and say why in a line under the field linked with aria-describedby. Disabled dims the field to 40 % and ignores pointer and keyboard.
Previews in these docs
The list is portalled to the end of the document and floats over the page. The previews here draw it inside the card so it stays contained, and show it only while the whole card is on screen.
Motion
The list appears and disappears at once. Nothing else moves: the border and focus ring change colour quickly.
Reduced motion
There is no movement to remove, so reduced motion changes nothing. The colour change is a short fade and stays.

Anatomy

The parts of an autocomplete, numbered in the figure, with the list open. The empty line replaces the list when nothing matches, and the portal is listed below.

  • data-slot="autocomplete"

    The root. It holds the field's text, the items and the filter and renders nothing itself; the value is the text in the input, not a chosen item.

  • data-slot="autocomplete-input-group"Optional

    The bordered frame around the input, 36 px high with an 8 px corner. It draws the border and focus ring, dims when disabled and turns red when invalid, so put an icon beside the input inside it.

  • data-slot="autocomplete-input"

    The text input. Typing filters the suggestions, arrow keys move through them, Enter takes one and Escape closes the list; give it a visible label or an aria-label.

  • data-slot="autocomplete-popup"

    The suggestion panel. It brings its own portal and positioner, matches the field's width and scrolls when it runs out of room.

  • data-slot="autocomplete-list"

    Renders the items. Pass a render function as the child so the filtered list, not the full one, is mapped.

  • data-slot="autocomplete-item"

    One suggestion, 32 px high for a single line, whose value fills the field when chosen. A row can hold an icon, or an avatar and a second line, and the highlighted row gets the page fill.

  • data-slot="autocomplete-empty"Optional

    A centred line shown in place of the list when nothing matches. It is hidden while it has no content.

  • Optional

    Moves the list to the end of the document. The popup already uses it; you only need it for a custom container.

Best practices

  • Do

    Give the input a visible label. The placeholder is a hint such as Search cities, not the name of the field.

  • Do

    Always add an empty-state line with a sentence like No cities match, so a list without matches never looks broken.

  • Do

    Control the value with state when the text drives something else, such as a server search. The value is the text of the field, never an item object.

  • Do

    Keep the suggestions few, five to eight, and one line each. Cap a long list with a limit; people pick by reading, so rows with several lines or controls slow them down.

  • Don’t

    Don't treat the value as validated. Text that matches no suggestion still ends up in the value, so check it on submit or use a Combobox.

  • Don’t

    Don't use it for a choice that must come from the list. A Combobox keeps the field on a value of the list and tells people when nothing matches.

  • Don’t

    Don't use it as a menu of actions. Suggestions fill a field; actions belong in a Dropdown Menu.

API reference

Autocomplete wraps the Base UI autocomplete and passes its props on. The root takes the items and the field text; the input takes the props of a native input.

The root. It holds the field's text, the items and the filter and renders nothing itself; the value is the text in the input, not a chosen item.

PropTypeDefaultDescription
itemsreadonly ItemValue[] | readonly Group<ItemValue>[]—The suggestions: a flat array of strings or objects. The list filters them as the person types; the render function of receives the ones that match.
valueAriaCombobox.Props<ComponentProps<"input">["value"], "none">["inputValue"]—The text in the field, as a string. It is a controlled value: update it in .
defaultValueAriaCombobox.Props<ComponentProps<"input">["defaultValue"], "none">["defaultInputValue"]—The text the field starts with when you do not control it.
onValueChange(value, eventDetails) => void—Called with the new text each time the person types, clears the field or takes a suggestion.
filterAriaCombobox.Props<ItemValue, "none">["filter"]—Replaces the matching rule. It receives an item, the typed text and the function that turns an item into text, and returns whether the item stays in the list.
itemToStringValue(itemValue) => string—Turns an object item into the text of the field and of the submitted form. Needed when the items are objects.
autoHighlightboolean | "always"falseHighlights the first matching suggestion so Enter takes it. does it after the person types; does it whenever the list opens.
limitnumber-1The most suggestions the list shows. , the default, shows every match.
openboolean—Whether the list is open, when you control it. Pair it with .
defaultOpenbooleanfalseWhether the list starts open when you do not control it.
onOpenChange(open, eventDetails) => void—Called when the list opens or closes, with the reason, such as typing, a key press, an outside press or choosing a suggestion.
openOnInputClickbooleanfalseOpens the list when the field is clicked. Off by default: the list opens on typing and on the arrow keys.
mode"list" | "both" | "inline" | "none""list", the default, filters the suggestions and leaves the text alone. also completes the text inline, only completes inline, and shows the list without filtering.
disabledbooleanfalseDisables the field: it dims to 40 % and ignores the pointer and the keyboard.
readOnlybooleanfalseKeeps the text but stops people from choosing a suggestion.
requiredbooleanfalseMarks the field as required for the form it belongs to.
namestring—The name the text is submitted under in a form.
actionsRefRefObject<AutocompleteRootActions | null>—A ref to imperative actions. - : Manually unmounts the autocomplete. Call this after any externally controlled closing animation finishes.
childrenReactNode—
filteredItemsreadonly ItemValue[] | readonly Group<ItemValue>[]—Filtered items to display in the list. When provided, the list uses these items instead of filtering the prop internally. When is also provided, this array must preserve its flat or grouped structure. Nullish entries are no…
formstring—Identifies the form that owns the internal input. Useful when the autocomplete is rendered outside the form.
gridbooleanfalseWhether list items are presented in a grid layout. When enabled, arrow keys navigate across rows and columns inferred from DOM rows.
highlightItemOnHoverbooleantrueWhether moving the pointer over items should highlight them. Disabling this prop allows CSS to be differentiated from the () state.
idstring—The id of the component.
inlinebooleanfalseWhether the list is rendered inline without using the component's own popup. Specify unconditionally in conjunction with this prop so the list is considered visible:
inputRefRef<HTMLInputElement>—A ref to the hidden input element.
keepHighlightbooleanfalseWhether the highlighted item should be preserved when the pointer leaves the list.
localeIntl.LocalesArgument—The locale to use for string comparison. Defaults to the user's runtime locale.
loopFocusbooleantrueWhether to loop keyboard focus back to the input when the end of the list is reached while using the arrow keys. The first item can then be reached by pressing <kbd>ArrowDown</kbd> again from the input, or the last item can be reached by p…
modalbooleanfalseDetermines if the popup enters a modal state when open. - : user interaction is limited to the popup: document page scroll is locked and pointer interactions on outside elements are disabled. - : user interaction with the rest…
onItemHighlighted(highlightedValue, eventDetails) => void—Callback fired when an item is highlighted or unhighlighted. Receives the highlighted item value (or if no item is highlighted) and event details with a property describing why the highlight changed. The can b…
onOpenChangeComplete(open) => void—Event handler called after any animations complete when the popup is opened or closed.
submitOnItemClickAriaCombobox.Props<ItemValue, "none">["submitOnItemClick"]falseWhether clicking an item should submit the autocomplete's owning form. By default, clicking an item via a pointer or <kbd>Enter</kbd> key does not submit the owning form. Useful when the autocomplete is used as a single-field form search i…
virtualizedbooleanfalseWhether the items are being externally virtualized.

The bordered frame around the input, 36 px high with an 8 px corner. It draws the border and focus ring, dims when disabled and turns red when invalid, so put an icon beside the input inside it.

PropTypeDefaultDescription
classNamestring | (state) => string | undefined—Extra classes for the frame, for example for a fixed width or for the large height.

The text input. Typing filters the suggestions, arrow keys move through them, Enter takes one and Escape closes the list; give it a visible label or an aria-label.

PropTypeDefaultDescription
classNamestring | (state) => string | undefined—Extra classes for the input inside the frame.
disabledbooleanfalseDisables this input only. Prefer on the root, which also dims the frame.

The suggestion panel. It brings its own portal and positioner, matches the field's width and scrolls when it runs out of room.

PropTypeDefaultDescription
classNamestring | (state) => string | undefined—Extra classes for the list panel, for example to make it wider than the field.
finalFocusboolean | RefObject<HTMLElement | null> | (closeType) => unknown—Where focus goes when the list closes. It stays in the input by default.
initialFocusboolean | RefObject<HTMLElement | null> | (openType) => unknown—Where focus goes when the list opens. It stays in the input by default, so people can keep typing.

Renders the items. Pass a render function as the child so the filtered list, not the full one, is mapped.

PropTypeDefaultDescription
childrenReactNode | (item, index) => ReactNode—A render function, , that receives the items that match.
classNamestring | (state) => string | undefined—Extra classes for the list element inside the panel.

One suggestion, 32 px high for a single line, whose value fills the field when chosen. A row can hold an icon, or an avatar and a second line, and the highlighted row gets the page fill.

PropTypeDefaultDescription
valueanynullThe item this row stands for, the same string or object as in . It is what fills the field when the row is chosen.
disabledbooleanfalseStops the row from being highlighted or chosen.
onClickBaseUIComponentProps<"div", AutocompleteItemState>["onClick"]—Called when the row is clicked or taken with Enter.
classNamestring | (state) => string | undefined—Extra classes for the row, for example for a row with an avatar.
childrenReactNode—
indexnumber—The index of the item in the list. Improves performance when specified by avoiding the need to calculate the index automatically from the DOM.
nativeButtonbooleanfalseWhether the component renders a native element when replacing it via the prop. Set to if the rendered element is a native button.

A centred line shown in place of the list when nothing matches. It is hidden while it has no content.

PropTypeDefaultDescription
classNamestring | (state) => string | undefined—Extra classes for the line shown when nothing matches.

Moves the list to the end of the document. The popup already uses it; you only need it for a custom container.

PropTypeDefaultDescription
containerHTMLElement | ShadowRoot | RefObject<HTMLElement | ShadowRoot | null> | null—The element the list is moved into. The end of the document by default.
keepMountedbooleanfalseKeeps the list in the DOM while it is closed.

Notes for AI

Give your coding assistant the Markdown reference instead of screenshots.

MCPget_component("autocomplete")
Installnpx wunderui-cli add autocomplete

The full library index for assistants is at /llms.txt.