Skip to
Keyboard shortcuts

Use the up and down arrow keys to move between items. Press Alt+Shift+K to open this list again.

Alpha version out now. The API may still change.

Autocomplete

A text field that suggests as the user types. The value is the text itself, so the user can write something that is not in the list.

Package
@kvirn-ui/react
Pattern
APG Combobox (editable, list autocomplete)
Testing
Automated. Core 0 of 2, Release 0 of 3

When to use it#

  • Use an Autocomplete for free text where suggestions help, such as a street name, and where any text is a valid answer.
  • Picking a suggestion only fills the input. Nothing is chosen from a list, so check the text yourself.
  • When only one of the options is a valid answer, use a Combobox. For a short list, use a Listbox or radio buttons.
  • The browser can also suggest from its own history. Set autoComplete on the input only when the field is for a known purpose and your suggestions add something.

Example#

Start typing. You can also write a street that is not in the list.

Use cases#

Keeping the text in your state

The value is the text. Pass value and onValueChange to keep it in your own state, here to show what the user entered. A suggestion that is picked and a typed text arrive the same way.

You entered:

Props in this example:

A required answer with an error

Mark the Field as required and check the text when the user sends the form. Any text is a valid answer, so the usual error is an empty field. Set invalid and say what to do. An invalid field keeps its error edge and shows the focus ring whenever it has focus.

Props in this example:

Warning: Don't forget

The field never moves focus. After a failed send, move it to the input: an error is read only when its field gets focus, so without the move a screen reader user isn’t told what went wrong (3.3.1 Error Identification).

Suggestions from your server

When the suggestions live on a server, turn the filter off, pass isLoading while you fetch and keep the last result in items. You write the fetch, and a short pause so it starts only when typing stops.

Props in this example:

Your own filter

The default filter matches the text anywhere in a suggestion, in the provider’s locale. Pass a function to change the rule, here to match only the start.

Props in this example:

A second line in each suggestion

A suggestion can hold more than its name, such as the district of a street. The optional parts keep its name to its text, which is also what goes in the input when it is picked, and give the second line as a description.

Props in this example:

Sending the text in a plain form

The text is the value, so the input itself carries the name and a plain form sends it. There is no hidden input. Enter with no active suggestion is the browser’s own, so the form is sent with whatever was typed.

Props in this example:

Warning: Don't forget

If the field asks for the user’s own street address, set autoComplete to the matching token, as here (1.3.5 Identify Input Purpose). The browser’s own suggestions then appear too, so do it only when yours add something.

Thousands of suggestions

Let the typing narrow the list first. If it stays long, virtualize renders only the suggestions in view plus the active one. Each tells a screen reader how many suggestions there are and its place in the list.

Props in this example:

Accessibility#

What it does for you#

  • Scope: Autocomplete, a text field that suggests. Autocomplete.Root with Autocomplete.Input and Autocomplete.Popup is the editable combobox for free text. The value is the text, which may match nothing. Autocomplete is built from the same hook, input and popup as Combobox, so its parts are the Combobox's, and the roles, states and keys that are the same are on the Combobox page. This page lists what differs, and has its own Keyboard table. The popup parts (Popup, List, Option, Group, GroupLabel, Empty) are the Listbox's: see the Listbox page.
  • APG pattern: Combobox: Editable Combobox With List Autocomplete (aria-autocomplete="list", manual selection), with Listbox for the popup's content.
  • Deviations: none from the APG keyboard practice. The choices below are allowed by the pattern: no suggestion is active until an arrow key, arrows don't wrap, Page Up and Page Down move ten, Home, End, ArrowLeft and ArrowRight stay with the text field and return visual focus to it (no suggestion stays active), Tab closes the popup without picking, a second Escape doesn't clear the text, and there is no inline completion. The optional Toggle and Clear are not tab stops, for the reasons given on the Combobox page.
  • Native elements used: <input type="text" role="combobox"> (Input), <div popover="manual"> (Popup), <div role="listbox"> (List), <div role="option">, <div role="group">, <button type="button"> (Toggle, Clear).

An Autocomplete is for a question whose answer is free text, where a list helps but isn't the answer: a street, a search, a place. The user types, suggestions appear, and they can pick one, which fills the field, or keep their own text. Suggestions never block other text: with no suggestion highlighted, Enter is the browser's own, so a form submits what was typed. The value is the text itself: value, defaultValue and onValueChange are yours, or defaultValue and name for a plain <form>, where the input carries the name. It is never turned into a key. If the answer must be one of the options, use a Combobox.

The parts and their roles are the Combobox's (see the Combobox page): Autocomplete.Control, Input, Toggle and Clear render the same elements with the classes kv-autocomplete-control, kv-autocomplete-input, kv-autocomplete-toggle and kv-autocomplete-clear. What differs:

PartElement / roleARIA / stateNotes
Autocomplete.RootnonenoneOwns items or groups, itemToString, itemToKey, isItemDisabled, filter, isLoading, value / defaultValue / onValueChange(text, { reason }), name, disabled, id, open / defaultOpen / onOpenChange(open, { reason }), placement, offset, padding, announcementDebounceMilliseconds, messages. No multiple and no hidden inputs, and itemToKey only tells options apart: it is never the value
Autocomplete.Input<input type="text" role="combobox">as the Combobox's: aria-autocomplete="list", aria-expanded, aria-controls, aria-activedescendant, aria-describedby, aria-invalid, aria-required, disabledCarries name when the Root has one. Its value is the text. autocomplete="off" unless you set your own (street-address, address-line1)
Autocomplete.Popup<div popover="manual">, no roledata-open, data-placement, data-loadingThe shell, as the Combobox's. Opens for text, and for ArrowDown, ArrowUp, Alt+ArrowDown and the Toggle. Closes when the text is empty
Autocomplete.List<div role="listbox">, always in the DOMnamed by the Field's label (or your aria-label on the List). No aria-multiselectable. hidden and data-empty while the popup is open with no suggestionThe element aria-controls points at, and the one that scrolls
Autocomplete.Option<div role="option">aria-selected="false" always: nothing is "chosen", because picking a suggestion only fills the input. aria-disabled, data-active, data-disabledThe suggestion's text is what goes in the input
Autocomplete.Empty<div>, plain text, no rolenoneShown while the popup is open and nothing matches: "No results", beside the hidden List, never inside the listbox. For free text that isn't an error, so leave it out when you don't want to say it (the count is still announced)
Autocomplete.Clear<button type="button" tabindex="-1">aria-label (combobox.clear)Empties the text and closes the popup. Rendered only while there is text. Not a tab stop
useAutocompletethe same attributes, for your own elementsthe same as useCombobox's, without the value listOptions as the Root

Rules, tested in autocomplete.test.tsx:

  • The same ARIA 1.2 combobox as a Combobox (autocomplete.test.tsx › a closed autocomplete: a native input wired to a hidden listbox popup). Named by <label for>, described by the help text and error (autocomplete.test.tsx › the Field’s label names the input, and the help text describes it). aria-activedescendant always points at a rendered option (autocomplete.test.tsx › aria-activedescendant always points at a rendered option).
  • Picking a suggestion fills the input and closes the popup, with the reason 'selection'; no option is ever aria-selected (autocomplete.test.tsx › Enter on an active suggestion fills the input and closes the popup, autocomplete.test.tsx › no suggestion is selected, and Autocomplete.Empty says "No results" when nothing matches).
  • Suggestions never block other text. Enter with no active suggestion is not intercepted, and the form submits what was typed (autocomplete.test.tsx › Enter with no active suggestion is the browser’s own: the form submits what was typed).
  • The text is never cleared silently. Escape, Tab and a blur keep it (autocomplete.test.tsx › the text is never cleared silently: Escape and Tab keep it). Only the Clear button empties it, and then the popup closes.
  • No suggestion, no expanded. With no suggestion and nothing loading the input reports aria-expanded="false" and the List is hidden, as the APG closes the listbox when there is nothing to show. The popup may still show the Empty text (autocomplete.test.tsx › with no suggestion and nothing loading the input reports collapsed, with or without Empty), and the theme draws nothing when there is no Empty either.
  • The popup opens for text and closes again when the text is emptied (autocomplete.test.tsx › the popup opens for text, and closes again when the text is emptied). A click on the input doesn't open it.
  • Filtering is on the label, anywhere in it, in the provider's locale (autocomplete.test.tsx › the suggestions are filtered in the provider’s locale: å, ä and ö are not a and o in Swedish). Your own filter replaces it, and filter={false} plus isLoading serves suggestions that the server has chosen.
  • No form state. The text is controlled with value, or uncontrolled with defaultValue (autocomplete.test.tsx › controlled: shows the text it is given, and a refused change is pulled back). With name the input carries it, and there is no hidden input (autocomplete.test.tsx › with a name, the input itself carries the text, and there is no hidden input).
  • Server rendering. The server writes the input with its text, a closed popup and no options (autocomplete.test.tsx › the server markup has the input with its text, a closed popup and no options).
  • Development warnings: as the Combobox's.

What you need to do#

  • A Field.Label with a visible question, always. A placeholder is not a label. Outside a Field, give the input aria-label or aria-labelledby.
  • Pass items (or groups) and a stable itemToString. For server suggestions pass filter={false}, isLoading, and your own debounce and fetch; keep the last result in items while the next one loads.
  • Set the right autoComplete where the field is for a known purpose (street-address, address-line1; 1.3.5 Identify Input Purpose (AA)) and know that the browser's own suggestions then compete with yours: use it only when ours add something.
  • Validate the text yourself. An Autocomplete does not require a suggestion, so don't say "Choose an option in the list" here; use a Combobox when only an option is valid.
  • Don't submit, navigate or move focus when a suggestion is picked or the text changes (3.2.2 On Input (A)).
  • Pass value and onValueChange, or defaultValue and name for a plain <form>.
  • For thousands of suggestions, let the typing narrow them first, and use virtualize only for what stays long. Give Autocomplete.List a height limit and overflow-y: auto (the default theme does), render it with a function child, and don't use groups: see Virtualization.

Warning: Don't forget

Give the input a visible Field.Label. A placeholder is not a label: it disappears when the user types (3.3.2 Labels or Instructions; 4.1.2 Name, Role, Value).

Visual and modes#

As the Combobox's, including the focus indicator. On keyboard focus, and on any focus that a pointer did not cause, a ring at least 2px thick, set off from the field, with at least 3:1 contrast against the adjacent colours (2.4.7 Focus Visible (AA); 2.4.13 Focus Appearance (AAA)). Before the script runs the browser's own keyboard-focus rule does the same. After a click the field shows a thicker edge in the focus colour and no ring, except that an invalid field shows the ring on any focus, keeping its thick error edge. In forced colours (Windows contrast themes) the focused edge uses the system highlight colour. The input looks like an Input, and the popup like the Listbox's. The Toggle and Clear buttons are at least 24 × 24 CSS px, and larger in the default theme (2.5.8 Target Size (Minimum) (AA)). The active suggestion has a bar at its inline start and a tinted fill, never colour alone (1.4.1 Use of Color (A)), and uses the system highlight colours in forced colours. Nothing moves under reduced motion. At 320px the input fits its column, and the popup is at least as wide as the input and never wider than the viewport (1.4.10 Reflow (AA)). In right-to-left text the chevron and the tick are at the inline end.

Focus management#

  • Initial focus: not moved. Opening never moves DOM focus, and no suggestion is active until ArrowDown or ArrowUp (opening with a key activates the first or last, so the user can see where they are).
  • Trap: no. The popup is not modal and the page behind it is not inert. Tab always leaves the input and closes the popup without picking (2.1.2 No Keyboard Trap (A)).
  • Restore to: the input, which never lost focus. Escape, a press on a suggestion, Toggle and Clear keep it there. A press outside leaves focus where the press put it.
  • Never obscured by: the popup is placed under the input (or its Control) and flips above it when there is no room, so it never covers the field (2.4.11 Focus Not Obscured (Minimum) (AA)). Its height is limited to the room that is left, and it scrolls inside. The active suggestion is scrolled into view when a key moves it.

Virtualization#

virtualize is off by default. It renders only the suggestions that are scrolled into view, for a flat list of thousands. An Autocomplete suggests as the user types, so the list is often short: virtualize a list that stays long after filtering. The rules are the Combobox's (see Virtualization on the Combobox page):

  • Keep what matters mounted. The active suggestion is always rendered, even when it is scrolled out of view, so aria-activedescendant on the input never points at nothing (4.1.2 Name, Role, Value (A); autocomplete-virtual.test.tsx › virtualized: ArrowDown and ArrowUp always leave aria-activedescendant on a suggestion in the page).
  • Scroll before you point. A key that moves the active suggestion scrolls to it, and the suggestion is rendered in the same commit that sets aria-activedescendant (2.4.3 Focus Order (A), 2.4.7 Focus Visible (AA); autocomplete-virtual.test.tsx › virtualized: ArrowUp activates the last suggestion, rendered and in view). A pointer move doesn't scroll.
  • Navigate the data, not the DOM. The arrows and Page Up and Page Down move through the whole list of suggestions (2.1.1 Keyboard (A); autocomplete-virtual.test.tsx › virtualized: PageDown and PageUp move ten suggestions that may not be rendered). Home and End still move the caret.
  • Expose the full size. Every rendered suggestion has aria-setsize and aria-posinset, and the size follows each keystroke (1.3.1 Info and Relationships (A); autocomplete-virtual.test.tsx › typing opens a list of 10 000 suggestions that mounts only a window, autocomplete-virtual.test.tsx › virtualized: typing narrows the suggestions, and the size of the set follows).
  • Flat lists only, off by default, inline geometry only. As in the Combobox: groups render in full with a development warning, unrendered suggestions can't be found with find in page or printed, and the list is the scroll element with a sizer inside it.
  • Screen-reader support varies. Test it with the screen readers your users have.

Rich options#

An option holds any markup. Autocomplete.OptionIcon, OptionText, OptionDescription and OptionIndicator are the Listbox's parts, and their contract is the Listbox's (Rich options): the name is the OptionText alone when there is one, the description is aria-describedby, the icon and indicator are aria-hidden. The active option is read through aria-activedescendant, and support for its description varies across screen readers, so the name must carry everything essential. Filtering uses itemToString, which should equal the OptionText. Tested in listbox-rich-options.test.tsx.

WCAG success criteria#

  • 1.3.1 Info and Relationships (A), 4.1.2 Name, Role, Value (A): the ARIA 1.2 combobox structure and the label. 1.3.5 Identify Input Purpose (AA): autoComplete.
  • 1.4.1 Use of Color (A), 1.4.10 Reflow (AA), 1.4.11 Non-text Contrast (AA): the active suggestion's bar, the field's edge and the 320px popup.
  • 1.4.13 Content on Hover or Focus (AA) does not apply: nothing appears on hover or focus alone.
  • 2.1.1 Keyboard (A), 2.1.2 No Keyboard Trap (A), 2.4.3 Focus Order (A), 3.2.1 On Focus (A), 3.2.2 On Input (A): the keys, one Tab stop, and no change of context when suggestions appear or one is picked.
  • 2.4.7 Focus Visible (AA), 2.4.11 Focus Not Obscured (Minimum) (AA), 2.4.13 Focus Appearance (AAA, not counted toward the AA bar): the focus ring, and a popup that never covers the field.
  • 2.5.3 Label in Name (A), 2.5.8 Target Size (Minimum) (AA): the Field's visible label is the name, and the size of Toggle and Clear.
  • 3.3.1 Error Identification (A), 3.3.2 Labels or Instructions (A), 3.3.3 Error Suggestion (AA): the Field's label, help text and error.
  • 4.1.3 Status Messages (AA): the result count, "no results" and "loading", polite and debounced.

Keyboard#

Focus
aria-activedescendant. DOM focus stays on the input, and the active suggestion is aria-activedescendant
Selection follows focus
no (Enter, Alt+ArrowUp or a click picks a suggestion, and the arrow keys only move the highlight)
Arrows wrap
no
Shortcuts
none

The input is one Tab stop. Toggle and Clear are not tab stops (tabindex="-1"): ArrowDown and Alt+ArrowDown open the popup, and the text can be selected and deleted. Home, End, ArrowLeft, ArrowRight and Space are the text field's own, and are never cancelled. The four caret keys also return visual focus to the field: the active suggestion is cleared and aria-activedescendant is removed, and the popup stays open. The arrows used here are vertical, so they do not flip in right-to-left text. A key that is not in this table is left to the browser, and Control and Command combinations are never taken.

KeyWhereWhat happens
Tabbefore the fieldMoves focus to the input. One stop
Test: autocomplete.test.tsx › Tab moves to the input, one stop
Shift+Tabon the input, popup closedMoves focus to the previous focusable element
Test: autocomplete.test.tsx › Shift+Tab leaves the input backwards
Tabdisabled inputSkips it (native disabled)
Test: autocomplete.test.tsx › Tab skips a disabled input
any characteron the inputTyped into the input: the suggestions are filtered to what contains the text, and the popup opens. Nothing is active, and nothing is announced until typing stops
Test: autocomplete.test.tsx › typing opens the popup with the matching suggestions, and focus stays on the input
ArrowDownon the input, popup closedOpens the popup with the suggestions for the current text (every one when the text is empty) and activates the first. Focus stays on the input
Test: autocomplete.test.tsx › ArrowDown on the closed input opens it with every suggestion and activates the first
ArrowUpon the input, popup closedOpens the popup and activates the last suggestion
Test: autocomplete.test.tsx › ArrowUp on the closed input activates the last suggestion
ArrowDownpopup openActivates the next suggestion, and scrolls it into view. Stops at the last
Test: autocomplete.test.tsx › arrows move the active suggestion and stop at the ends, and typing clears it
ArrowUppopup openActivates the previous suggestion. Stops at the first
Test: autocomplete.test.tsx › arrows move the active suggestion and stop at the ends, and typing clears it
PageDown / PageUppopup openMoves the active suggestion ten on or back, and stops at the last or the first
Test: autocomplete.test.tsx › PageDown and PageUp move ten suggestions and stop at the ends
Home / Endon the inputMove the caret in the text, as in any input. Visual focus returns to the field: no suggestion stays active and aria-activedescendant is removed
Test: autocomplete.test.tsx › Home, End, ArrowLeft, ArrowRight and Space are left to the input: the caret moves, and no suggestion stays active
ArrowLeft / ArrowRighton the inputMove the caret, as in any input, and leave no suggestion active. In right-to-left text they still only move the caret
Test: autocomplete.test.tsx › Home, End, ArrowLeft, ArrowRight and Space are left to the input: the caret moves, and no suggestion stays active
ArrowDown / ArrowUppopup open, right to leftStill the next and the previous suggestion: vertical arrows don't flip. ArrowLeft and ArrowRight only move the caret
Test: autocomplete.test.tsx › right to left: ArrowDown and ArrowUp still mean next and previous suggestion, and ArrowLeft and ArrowRight only move the caret
ArrowUpon the input, popup open, virtualizedActivates the last suggestion of the whole list, although it isn't rendered. It is rendered and scrolled into view, and aria-activedescendant points at it
Test: autocomplete-virtual.test.tsx › virtualized: ArrowUp activates the last suggestion, rendered and in view
ArrowDown / ArrowUppopup open, virtualizedMoves to the next or the previous suggestion of the whole list. Each is rendered before aria-activedescendant points at it, so the id always resolves to an element in the page
Test: autocomplete-virtual.test.tsx › virtualized: ArrowDown and ArrowUp always leave aria-activedescendant on a suggestion in the page
PageDown / PageUppopup open, virtualizedMoves the active suggestion ten on or back in the whole list. It is rendered, scrolled into view, and read with its place (aria-posinset of aria-setsize)
Test: autocomplete-virtual.test.tsx › virtualized: PageDown and PageUp move ten suggestions that may not be rendered
any characteron the input, virtualizedFilters the whole list, not only the suggestions that are rendered. The smaller list is still virtualized, and aria-setsize is the number that is left
Test: autocomplete-virtual.test.tsx › virtualized: typing narrows the suggestions, and the size of the set follows
Enterpopup open, a suggestion is activePicks it: its text fills the input and the popup closes. Focus stays
Test: autocomplete.test.tsx › Enter on an active suggestion fills the input and closes the popup
Enterpopup open and none active, or popup closedNothing from us: the browser's own Enter, so a form submits what was typed
Test: autocomplete.test.tsx › Enter with no active suggestion is the browser’s own: the form submits what was typed
Spaceon the inputTypes a space. It never picks a suggestion
Test: autocomplete.test.tsx › Home, End, ArrowLeft, ArrowRight and Space are left to the input: the caret moves, and no suggestion stays active
Escapepopup openCloses the popup. The text stays, and focus stays on the input. A second Escape does nothing
Test: autocomplete.test.tsx › the text is never cleared silently: Escape and Tab keep it
Escapepopup closedNothing: the key is the page's own
Test: autocomplete.test.tsx › Escape does nothing when the popup is closed
Alt+ArrowDownon the inputOpens the popup without activating a suggestion
Test: autocomplete.test.tsx › Alt+ArrowDown opens without activating, and Alt+ArrowUp picks the active suggestion
Alt+ArrowUppopup openPicks the active suggestion and closes the popup
Test: autocomplete.test.tsx › Alt+ArrowDown opens without activating, and Alt+ArrowUp picks the active suggestion
Tabpopup openCloses the popup without picking the active suggestion, keeps the text, and moves focus to the next focusable element
Test: autocomplete.test.tsx › Tab closes the popup without picking the active suggestion, and moves focus on
Shift+Tabpopup openCloses the popup without picking, keeps the text, and moves focus to the previous focusable element
Test: autocomplete.test.tsx › Shift+Tab closes the popup without picking and moves focus back
ArrowDown / ArrowUppopup open, a disabled suggestionThe disabled suggestion can be reached and is read as unavailable. Enter and a click don't pick it
Test: autocomplete.test.tsx › a disabled suggestion can be reached and cannot be picked
Backspace / Deleteon the input, the text becomes emptyDeletes text as in any input. The popup closes when the text is empty
Test: autocomplete.test.tsx › the popup opens for text, and closes again when the text is emptied
Pointer presson a suggestionPicks it, and keeps focus on the input. A disabled suggestion does nothing
Test: autocomplete.test.tsx › a click on a suggestion fills the input, closes the popup and keeps focus on the input
Pointer moveover a suggestionMakes it the active suggestion
Test: autocomplete.test.tsx › moving the pointer over a suggestion makes it active
Pointer presson ToggleOpens the popup, or closes it when it is open. Focus stays on, or goes to, the input. Nothing is active
Test: autocomplete.test.tsx › Toggle opens the popup with every suggestion, and is not a tab stop
Pointer presson ClearEmpties the text and closes the popup. Focus stays on, or goes to, the input
Test: autocomplete.test.tsx › the Clear button empties the text, closes the popup and keeps focus on the input
Pointer pressoutside the popup, the input and its buttonsCloses the popup. A control that is pressed keeps the focus
Test: autocomplete.test.tsx › a press outside closes the popup, and focus stays where the press put it
Pointer presson the Field's labelFocuses the input and opens nothing
Test: autocomplete.test.tsx › clicking the label focuses the input and opens nothing

Announcements#

Autocomplete tells screen reader users about these changes without moving focus. Each message waits until the screen reader is quiet (polite) or interrupts it (assertive).

WhenWhat it saysMessage keyPoliteness
The popup is open and there are N suggestionscombobox.resultCountPolite
The popup is open and nothing matchescombobox.noResultsPolite
The popup is open and the suggestions are loadingcombobox.loadingPolite

The text in all five languages

Change the text#

For your whole app, pass messages to KvirnProvider. For one Autocomplete, pass its messages prop.

<KvirnProvider messages={{ combobox: { resultCount: '…' } }}>

Warning: Don't forget

Announcements need a KvirnProvider around your app, outside any <form>, or an Announcer of your own. Without one nothing is announced, and a development warning says so.

API reference#

import { Autocomplete, useAutocomplete } from '@kvirn-ui/react'

Autocomplete.Root

Renders no element of its own. Put an Autocomplete.Input and an Autocomplete.Popup inside it, in a Field, the popup right after the input. Its value is the text. Picking a suggestion fills the input and closes the popup.

PropTypeDefaultDescription
itemsreadonly TItem[]–A flat list of any item type. Memoize a list you build in render: items are compared by identity. Ignored when groups is given.
groupsreadonly { key: string; label: string; items: readonly TItem[] }[]–Items in named groups, instead of items. Groups do not nest.
itemToString(item: TItem) => stringString(item)The text of an item: shown in the list, matched by the filter, and put in the input when it is picked.
itemToKey(item: TItem) => stringitemToStringA stable, unique key that identifies an option in the list. The default is its text, so give one only when two items share a text.
isItemDisabled(item: TItem) => boolean–A disabled option stays reachable with the arrow keys and cannot be chosen.
filter((item: TItem, query: string) => boolean) | falseMatches the query anywhere in the textReplaces the default filter, which uses the provider’s locale (å, ä and ö are not a and o in Swedish). false turns filtering off, for results your server has already filtered: pass isLoading while it works.
isLoadingbooleanfalseThe options are being fetched. The popup shows and announces “loading”, and sets data-loading. items may still hold the last result.
valuestring–Controlled: the text. It may match no suggestion.
defaultValuestring–Uncontrolled: the text to begin with.
onValueChange(value: string, { reason: 'input' | 'selection' | 'clear' }) => void–Called with the text when the user types, picks a suggestion (it fills the input) or clears. It only reports: update value yourself when it is controlled.
namestring–Put on the input itself, so a plain form sends the text.
disabledbooleanfalseDisables it. A disabled Field disables it too.
idstring–The input’s id, outside a Field. Inside one, the Field’s id is used.
openboolean–Controlled: whether the popup is open. Pair it with onOpenChange.
defaultOpenbooleanfalseUncontrolled: whether the popup starts open.
onOpenChange(open: boolean, { reason }) => void–Called when the user opens or closes the popup. reason is input, key, escape, toggle-press, option-press, outside-press, blur, light-dismiss or clear. It only reports.
placementPlacement'bottom-start'Where the popup goes when there is room. It flips when it does not fit.
offsetnumber4The gap between the field and the popup, in pixels.
paddingnumber8The space kept to the edge of the viewport, in pixels.
announceResultsbooleantrueWhether the result count, "no results" and "loading" are announced. Turn it off only when you announce the list state yourself, or the user hears it twice.
announcementDebounceMillisecondsnumber500How long to wait after the last change before the result count is announced. Nothing is announced while the user types.
messagesPartial<KvirnMessages['combobox']>–Per-instance text: the result count, “no results”, “loading” and the names of the buttons.
virtualizeboolean | { estimateSize?: number; overscan?: number }falseRenders only the options in view, plus the active and the chosen one, for a flat list of thousands. estimateSize defaults to 44 pixels and overscan to 5. Not with groups. Let the user filter first.

Autocomplete.Control

Renders <div> with no role, around the input and its Toggle and Clear. It is optional. The popup is placed against it and is as wide as it, and the default theme draws the field’s edge and focus ring on it. It takes every attribute of a <div> and passes ref to it. Theming is on Theming.

Class or attributeValuesMeaning
kv-autocomplete-controlalwaysThe part class. The default theme draws the field’s edge on it.
data-openpresent or absentThe popup is open.
data-focus-visiblepresent or absentThe input has keyboard focus (:focus-visible).
data-invalidpresent or absentThe Field is invalid.
data-requiredpresent or absentThe Field is required.
data-disabledpresent or absentThe Combobox is disabled.

Autocomplete.Input

Renders <input type="text" role="combobox" aria-autocomplete="list">, named by the Field’s label. Focus stays on it. Its autoComplete is off unless you set your own, and it carries the Root’s name.

Class or attributeValuesMeaning
kv-autocomplete-inputalwaysThe part class.
data-openpresent or absentThe popup is open.
data-focusedpresent or absentThe input has focus, however it got it.
data-focus-visiblepresent or absentThe input has keyboard focus (:focus-visible).
data-invalidpresent or absentThe Field is invalid.
data-requiredpresent or absentThe Field is required.
data-disabledpresent or absentThe Combobox is disabled.

Autocomplete.Toggle

Renders <button type="button" tabindex="-1"> that opens and closes the popup, named “Show options” (combobox.showOptions). It is optional and not a tab stop.

Class or attributeValuesMeaning
kv-autocomplete-togglealwaysThe part class. The default theme draws a chevron.
data-openpresent or absentThe popup is open.
data-disabledpresent or absentThe Toggle is disabled.

Autocomplete.Clear

Renders <button type="button" tabindex="-1"> that empties the text, named “Clear” (combobox.clear). It renders only while there is text. It is optional and not a tab stop.

Class or attributeValuesMeaning
kv-autocomplete-clearalwaysThe part class.
data-disabledpresent or absentThe Clear button is disabled.

Autocomplete.Popup

Renders <div popover="manual"> with no role, in the top layer: the same part as Listbox.Popup. Focus never enters it.

Class or attributeValuesMeaning
kv-listbox-popupalwaysThe part class. Combobox and Autocomplete keep it.
data-openpresent or absentThe popup is open.
data-placementa placement, such as bottom-startThe side the popup is on now, after it flipped.
data-detachedpresent or absentThe anchor is scrolled out of view, so the popup is hidden.
data-loadingpresent or absentThe popup is open and isLoading is on.

Autocomplete.List

Renders <div role="listbox"> inside the popup: the same part as Listbox.List.

PropTypeDefaultDescription
childrenReactNode | (item: TItem, entry: ListboxEntry<TItem>) => ReactNode–A function that renders one Option per item (or a Group per group). Options render only while the popup is open.
Class or attributeValuesMeaning
kv-listbox-listalwaysThe part class. This is the part that scrolls.
data-emptypresent or absentThe popup is open and there is no option, so the list is hidden.
data-virtualizedpresent or absentOnly some options are rendered.
kv-listbox-virtual-sizeralwaysInside a virtualized list: one element with the height of the whole list.

Autocomplete.Option

Renders <div role="option">: the same part as Listbox.Option. No suggestion is ever chosen (aria-selected stays false): picking one fills the input.

PropTypeDefaultDescription
itemTItemRequiredOne of the Root’s items, as List hands it to you.
childrenReactNodeThe item’s textYour own content for a rich option. Its name is then its text content.
Class or attributeValuesMeaning
kv-listbox-optionalwaysThe part class.
langa language code, or absentFrom itemToLang.
data-activepresent or absentThe option the arrow keys are on (aria-activedescendant).
data-selectedpresent or absentThe option is chosen.
data-disabledpresent or absentThe option cannot be chosen.
data-has-indicatorpresent or absentThe option holds an OptionIndicator.
data-indexa numberIn a virtualized list: the option’s place in the whole list.

Autocomplete.OptionIcon

Renders <span aria-hidden="true">: the same part as Listbox.OptionIcon.

Class or attributeValuesMeaning
kv-listbox-option-iconalwaysThe part class.

Autocomplete.OptionText

Renders <span> that names the suggestion: the same part as Listbox.OptionText.

Class or attributeValuesMeaning
kv-listbox-option-textalwaysThe part class.

Autocomplete.OptionDescription

Renders <span> that describes the suggestion: the same part as Listbox.OptionDescription.

Class or attributeValuesMeaning
kv-listbox-option-descriptionalwaysThe part class.

Autocomplete.OptionIndicator

Renders <span aria-hidden="true">: the same part as Listbox.OptionIndicator.

Class or attributeValuesMeaning
kv-listbox-option-indicatoralwaysThe part class.
data-selectedpresent or absentThe option is chosen.

Autocomplete.Group

Renders <div role="group">: the same part as Listbox.Group.

PropTypeDefaultDescription
sectionListboxSection<TItem>RequiredThe group, as the Root hands it out. List passes it for you.
childrenReactNode | (item: TItem, entry: ListboxEntry<TItem>) => ReactNode–A function renders the label, then one child per option.
Class or attributeValuesMeaning
kv-listbox-groupalwaysThe part class.

Autocomplete.GroupLabel

Renders <div> with the group’s name: the same part as Listbox.GroupLabel.

Class or attributeValuesMeaning
kv-listbox-group-labelalwaysThe part class.

Autocomplete.Empty

Renders <div> with plain text, shown while the popup is open and nothing matches: the same part as Listbox.Empty. Its default text is “No results”, or “Loading results” while isLoading is on.

Class or attributeValuesMeaning
kv-listbox-emptyalwaysThe part class.

useAutocomplete

Options

PropTypeDefaultDescription
itemsreadonly TItem[]–A flat list of any item type. Memoize a list you build in render: items are compared by identity. Ignored when groups is given.
groupsreadonly { key: string; label: string; items: readonly TItem[] }[]–Items in named groups, instead of items. Groups do not nest.
itemToString(item: TItem) => stringString(item)The text of an item: shown in the list, matched by the filter, and put in the input when it is picked.
itemToKey(item: TItem) => stringitemToStringA stable, unique key that identifies an option in the list. The default is its text, so give one only when two items share a text.
isItemDisabled(item: TItem) => boolean–A disabled option stays reachable with the arrow keys and cannot be chosen.
filter((item: TItem, query: string) => boolean) | falseMatches the query anywhere in the textReplaces the default filter, which uses the provider’s locale (å, ä and ö are not a and o in Swedish). false turns filtering off, for results your server has already filtered: pass isLoading while it works.
isLoadingbooleanfalseThe options are being fetched. The popup shows and announces “loading”, and sets data-loading. items may still hold the last result.
valuestring–Controlled: the text. It may match no suggestion.
defaultValuestring–Uncontrolled: the text to begin with.
onValueChange(value: string, { reason: 'input' | 'selection' | 'clear' }) => void–Called with the text when the user types, picks a suggestion (it fills the input) or clears. It only reports: update value yourself when it is controlled.
namestring–Put on the input itself, so a plain form sends the text.
disabledbooleanfalseDisables it. A disabled Field disables it too.
idstring–The input’s id, outside a Field. Inside one, the Field’s id is used.
openboolean–Controlled: whether the popup is open. Pair it with onOpenChange.
defaultOpenbooleanfalseUncontrolled: whether the popup starts open.
onOpenChange(open: boolean, { reason }) => void–Called when the user opens or closes the popup. reason is input, key, escape, toggle-press, option-press, outside-press, blur, light-dismiss or clear. It only reports.
placementPlacement'bottom-start'Where the popup goes when there is room. It flips when it does not fit.
offsetnumber4The gap between the field and the popup, in pixels.
paddingnumber8The space kept to the edge of the viewport, in pixels.
announceResultsbooleantrueWhether the result count, "no results" and "loading" are announced. Turn it off only when you announce the list state yourself, or the user hears it twice.
announcementDebounceMillisecondsnumber500How long to wait after the last change before the result count is announced. Nothing is announced while the user types.
messagesPartial<KvirnMessages['combobox']>–Per-instance text: the result count, “no results”, “loading” and the names of the buttons.
virtualizeboolean | { estimateSize?: number; overscan?: number }falseRenders only the options in view, plus the active and the chosen one, for a flat list of thousands. estimateSize defaults to 44 pixels and overscan to 5. Not with groups. Let the user filter first.

Result

PropTypeDefaultDescription
variant'autocomplete'–Always autocomplete here.
isOpenboolean–Whether the popup is open.
isMultipleboolean–Always false: an Autocomplete takes one text.
isDisabledboolean–From disabled or the Field.
isInvalidboolean–From the Field.
isRequiredboolean–From the Field.
isFocusVisibleboolean–Whether the input has keyboard (:focus-visible) focus.
isLoadingboolean–Whether the options are loading.
inputValuestring–What the input shows.
hasClearableValueboolean–There is text, so Clear has something to clear.
entriesreadonly ListboxEntry<TItem>[]–Every option the filter lets through, in order. index counts across groups.
sectionsreadonly ListboxSection<TItem>[] | undefined–The groups with their entries, or undefined for a flat list.
sizenumber–The number of options after filtering.
activeKeystring | undefined–The active option’s key. Undefined while closed and until the user moves.
selectedKeysreadonly string[]–Not used: no suggestion is ever chosen. Picking one fills the input.
selectedValuesreadonly ComboboxSelectedValue<TItem>[]–Not used: no suggestion is ever chosen.
emptyTextstring–The text of Combobox.Empty unless you give it children: combobox.noResults.
loadingTextstring–The text of the loading state: combobox.loading.
controlPropsComboboxControlPartProps–Spread on the box around the input. It anchors the popup when present.
inputPropsComboboxInputPartProps–Spread on an <input>: role combobox, ARIA, value and handlers.
togglePropsComboboxTogglePartProps–Spread on a <button> that opens and closes the popup. Not a tab stop.
clearPropsComboboxClearPartProps–Spread on a <button> that empties the text and the value. Not a tab stop.
valueListPropsComboboxValueListPartProps–Not used: an Autocomplete has no list of chosen values.
getValueProps(value: { key: string }) => ComboboxValuePartProps–Not used.
getRemoveButtonProps(value: ComboboxSelectedValue<TItem>) => ComboboxRemoveButtonPartProps–Not used.
popupPropsListboxPopupPartProps & { "data-loading"?: "" }–Spread on the popup: popover="manual", its id and ref. data-loading while loading.
listPropsListboxListPartProps–Spread on the role="listbox" element inside the popup.
emptyPropsListboxEmptyPartProps–Spread on the empty-state text.
getOptionProps(entry: ListboxOptionEntry) => ListboxOptionPartProps–The props of one option, from its entry.
getGroupProps(section: { key: string }) => ListboxGroupPartProps–The props of one group.
getGroupLabelProps(section: { key: string }) => ListboxGroupLabelPartProps–The props of one group’s label.
getEntry(item: unknown) => ListboxEntry<unknown> | undefined–The entry of an item that the list rendered, found by identity.
shouldScrollToActive() => boolean–False while the pointer moved the active option: it is already under it.
virtualizationListboxVirtualization | undefined–Set while virtualize is on, the popup is open and the list is flat.
hiddenInputsreadonly { name: string; value: string }[]–Always empty: the input carries the name.

Strings

These are the default texts in @kvirn-ui/i18n.

For your whole app, pass messages to KvirnProvider. For one Autocomplete, pass its messages prop.

combobox.resultCount

Announced, politely and after a pause, when the suggestions change because the user typed. The texts below use five results.

LanguageDefault text
Svenska5 resultat
Suomi5 tulosta
Norsk bokmål5 treff
Norsk nynorsk5 treff
English5 results

combobox.noResults

Announced when nothing matches, and the default text of Autocomplete.Empty.

LanguageDefault text
SvenskaInga resultat
SuomiEi tuloksia
Norsk bokmålIngen treff
Norsk nynorskIngen treff
EnglishNo results

combobox.loading

Announced while the suggestions are loading, and the text of Autocomplete.Empty then.

LanguageDefault text
SvenskaLaddar resultat
SuomiLadataan tuloksia
Norsk bokmålLaster treff
Norsk nynorskLastar treff
EnglishLoading results

combobox.clear

The name of the Clear button.

LanguageDefault text
SvenskaRensa
SuomiTyhjennä
Norsk bokmålTøm
Norsk nynorskTøm
EnglishClear

combobox.showOptions

The name of the Toggle button.

LanguageDefault text
SvenskaVisa alternativ
SuomiNäytä vaihtoehdot
Norsk bokmålVis alternativer
Norsk nynorskVis alternativ
EnglishShow options

Known issues#

  • aria-activedescendant on VoiceOver and TalkBack has known gaps. Someone using VoiceOver (Apple's screen reader) or TalkBack (Android's) may not hear the highlighted suggestion read. There is no native rendering, so test on iOS and Android with your users.
  • Filtering after a pick. After a suggestion is picked the list stays filtered by it until the text changes, so ArrowDown then shows the suggestions that contain that text. Empty the text to see them all.
  • Virtualization is opt-in and has limits. Suggestions that are not drawn can't be found with find in page or printed. See Virtualization above.
  • WebKit is not automated. The keyboard tests run in Chromium only. Safari's engine (WebKit) is not tested automatically. Check popover="manual", the outside press and Escape on Safari 17 yourself.

Information: Did you know?

Anything on this list that affects your service belongs in your accessibility statement, with the workaround. Public-sector sites in the EU must publish one (the Web Accessibility Directive).

Testing#

The automated tests prove the keyboard behaviour, the names and states, that axe finds no violations in every story and theme, and, for the components they cover, that the stories hold up in forced colours, reduced motion, text spacing and a 320 pixel width. An Automated row passes on these tests alone. A Core or Release row passes only when an automated agent check and a person on the real assistive technology have both checked it. "agent-verified" means automated tests in the repository (with a virtual screen reader for the screen reader rows), not the real assistive technology.

AT + browser + OSAgent checkHuman checkResultNotes
Automated (re-runnable tests)
axe, WCAG 2.2 A and AA, every story, 4 themespassn/apassautocomplete.stories.tsx, every story, 4 themes
Markup and ARIA (roles, names, ids, states)passn/apassautocomplete.test.tsx (axe and role, name and state): the Field’s label names the input, and the help text describes it
Keyboard contract rows (Vitest browser)passn/apass33 rows, each names a test in autocomplete.test.tsx
Focus order and managementpassn/apassautocomplete.test.tsx: typing opens the popup with the matching suggestions, and focus stays on the input
Display modes (forced colours, 320px reflow, text spacing, reduced motion)passn/apassthe four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI
Core (required for beta)
NVDA + Chrome + Windowspendingpendingpending
VoiceOver + Safari + iOSpendingpendingpending
Release (before 1.0 and each minor)
JAWS + Chrome + Windowspendingpendingpending
TalkBack + Chrome + Androidpendingpendingpending
VoiceOver + Safari + macOSpendingpendingpending

Questions for the manual testing with assistive technology: is the suggestion count read once, after typing stops, and not over the typed letters? Is a picked suggestion read as the input's new value? Does a screen reader user understand that other text is allowed, or should the help text say so? Does aria-activedescendant read each suggestion on VoiceOver (macOS and iOS) and TalkBack?