When to use it#
- Use a Combobox when the list is too long to scan and people can type a few letters to narrow it, such as a municipality, an authority or a country.
- The value is an option, so text that matches nothing leaves the value empty (
null). For free text that only gets suggestions, use an Autocomplete. - For up to about 15 options, a Listbox or radio buttons are easier. A Combobox always draws its own list, also on phones and tablets.
- Not for a list of actions or for going to a page. Use a Button or a Link.
Example#
Type a few letters, then choose one from the list.
import { Combobox, Field } from '@kvirn-ui/react'
import { municipalities } from '../listbox/data.ts'
import type { Municipality } from '../listbox/data.ts'
import { useComboboxTexts } from './texts.ts'
export function DefaultCombobox() {
const { texts } = useComboboxTexts()
return (
<Field.Root required>
<Field.Label>{texts.municipality}</Field.Label>
<Field.Prose>
<p>{texts.hint}</p>
</Field.Prose>
<Combobox.Root
items={municipalities}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
>
<Combobox.Control>
<Combobox.Input />
<Combobox.Clear />
<Combobox.Toggle />
</Combobox.Control>
<Combobox.Popup>
<Combobox.List>
{(municipality: Municipality) => <Combobox.Option item={municipality} />}
</Combobox.List>
<Combobox.Empty />
</Combobox.Popup>
</Combobox.Root>
</Field.Root>
)
}Use cases#
Choosing several options
With multiple, each choice moves out of the field into a list of values before the input, and the list of options stays open for the next one. Each value has a remove button, so people can take one back.
Choose as many as you like.
import { Combobox, Field } from '@kvirn-ui/react'
import { municipalities } from '../listbox/data.ts'
import type { Municipality } from '../listbox/data.ts'
import { useComboboxTexts } from './texts.ts'
export function SeveralCombobox() {
const { texts } = useComboboxTexts()
return (
<Field.Root>
<Field.Label>{texts.several}</Field.Label>
<Field.Prose>
<p>{texts.severalHint}</p>
</Field.Prose>
<Combobox.Root
multiple
items={municipalities}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
defaultValue={['malmo', 'uppsala']}
>
<Combobox.ValueList />
<Combobox.Input />
<Combobox.Popup>
<Combobox.List>
{(municipality: Municipality) => <Combobox.Option item={municipality} />}
</Combobox.List>
<Combobox.Empty />
</Combobox.Popup>
</Combobox.Root>
</Field.Root>
)
}Props in this example:
multipleon Combobox.RootdefaultValueon Combobox.Root
Results from your server
When the list lives on a server, turn the filter off with filter, 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. The list shows “Loading results” and a screen reader (software that reads the screen aloud) says it.
Type a few letters, then choose one from the list.
import { Combobox, Field } from '@kvirn-ui/react'
import { useEffect, useRef, useState } from 'react'
import { municipalities } from '../listbox/data.ts'
import type { Municipality } from '../listbox/data.ts'
import { useComboboxTexts } from './texts.ts'
// Stands in for your server: it answers after a short wait.
const search = (query: string) =>
municipalities.filter((municipality) =>
municipality.name.toLowerCase().includes(query.trim().toLowerCase()),
)
export function ServerResultsCombobox() {
const { texts } = useComboboxTexts()
const [results, setResults] = useState<readonly Municipality[]>([])
const [isLoading, setIsLoading] = useState(false)
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
useEffect(() => () => clearTimeout(timer.current), [])
return (
<Field.Root>
<Field.Label>{texts.municipality}</Field.Label>
<Field.Prose>
<p>{texts.hint}</p>
</Field.Prose>
<Combobox.Root
items={results}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
filter={false}
isLoading={isLoading}
onInputValueChange={(text, { reason }) => {
if (reason !== 'input') {
return
}
clearTimeout(timer.current)
if (text.trim() === '') {
setResults([])
setIsLoading(false)
return
}
setIsLoading(true)
timer.current = setTimeout(() => {
setResults(search(text))
setIsLoading(false)
}, 800)
}}
>
<Combobox.Control>
<Combobox.Input />
<Combobox.Clear />
</Combobox.Control>
<Combobox.Popup>
<Combobox.List>
{(municipality: Municipality) => <Combobox.Option item={municipality} />}
</Combobox.List>
<Combobox.Empty />
</Combobox.Popup>
</Combobox.Root>
</Field.Root>
)
}Props in this example:
filteron Combobox.RootisLoadingon Combobox.RootonInputValueChangeon Combobox.Root
Your own filter
The default filter matches what was typed anywhere in the text, in the provider’s language. Pass a function to filter to change the rule, here to match only the start. A new function applies from the next keystroke.
import { Combobox, Field } from '@kvirn-ui/react'
import { municipalities } from '../listbox/data.ts'
import type { Municipality } from '../listbox/data.ts'
import { useComboboxTexts } from './texts.ts'
export function OwnFilterCombobox() {
const { texts } = useComboboxTexts()
return (
<Field.Root>
<Field.Label>{texts.municipality}</Field.Label>
<Combobox.Root
items={municipalities}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
filter={(municipality, query) =>
municipality.name.toLowerCase().startsWith(query.trim().toLowerCase())
}
>
<Combobox.Control>
<Combobox.Input />
<Combobox.Clear />
<Combobox.Toggle />
</Combobox.Control>
<Combobox.Popup>
<Combobox.List>
{(municipality: Municipality) => <Combobox.Option item={municipality} />}
</Combobox.List>
<Combobox.Empty />
</Combobox.Popup>
</Combobox.Root>
</Field.Root>
)
}Props in this example:
filteron Combobox.Root
Text that matches nothing
The Combobox never clears what the user typed, and the value stays null. You decide when that is an error and say what to do. Here the field is invalid once it has been left with text that is not an option.
import { Combobox, Field } from '@kvirn-ui/react'
import { useState } from 'react'
import { municipalities } from '../listbox/data.ts'
import type { Municipality } from '../listbox/data.ts'
import { useComboboxTexts } from './texts.ts'
export function NotInListCombobox() {
const { texts } = useComboboxTexts()
const [value, setValue] = useState<string | null>(null)
const [text, setText] = useState<string>(texts.typedStart)
const [isTouched, setIsTouched] = useState(false)
const isInvalid = isTouched && text !== '' && value === null
return (
<Field.Root required invalid={isInvalid}>
<Field.Label>{texts.municipality}</Field.Label>
<Combobox.Root
items={municipalities}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
value={value}
onValueChange={setValue}
inputValue={text}
onInputValueChange={setText}
>
<Combobox.Control>
<Combobox.Input onBlur={() => setIsTouched(true)} />
<Combobox.Clear />
<Combobox.Toggle />
</Combobox.Control>
<Combobox.Popup>
<Combobox.List>
{(municipality: Municipality) => <Combobox.Option item={municipality} />}
</Combobox.List>
<Combobox.Empty />
</Combobox.Popup>
</Combobox.Root>
<Field.ErrorMessage>{texts.notInList}</Field.ErrorMessage>
</Field.Root>
)
}Props in this example:
valueon Combobox.RootonValueChangeon Combobox.RootinputValueon Combobox.RootonInputValueChangeon Combobox.Root
Information: Did you know?
Editing away from a chosen option’s text also makes the value null, and keeps what was typed. Apply onValueChange(null) when you control the value, or the old text is put back.
A second line in each suggestion
Use it when the name alone is not enough to choose. An option can hold any markup. The optional parts keep its name right: the text is the name and what goes in the input, and the description is read as help.
import { Combobox, Field } from '@kvirn-ui/react'
import { municipalities } from '../listbox/data.ts'
import type { Municipality } from '../listbox/data.ts'
import { useComboboxTexts } from './texts.ts'
export function RichOptionsCombobox() {
const { texts } = useComboboxTexts()
return (
<Field.Root>
<Field.Label>{texts.municipality}</Field.Label>
<Combobox.Root
items={municipalities}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
>
<Combobox.Input />
<Combobox.Popup>
<Combobox.List>
{(municipality: Municipality) => (
<Combobox.Option item={municipality}>
<Combobox.OptionText>{municipality.name}</Combobox.OptionText>
<Combobox.OptionDescription>{municipality.county}</Combobox.OptionDescription>
<Combobox.OptionIndicator />
</Combobox.Option>
)}
</Combobox.List>
<Combobox.Empty />
</Combobox.Popup>
</Combobox.Root>
</Field.Root>
)
}Props in this example:
childrenon Combobox.Option
Sending the choice in a plain form
KvirnUI holds no form state. Give the Root a name and each chosen key goes into the form as a hidden input, so FormData and a plain submit work.
import { Button, Combobox, Field } from '@kvirn-ui/react'
import { useState } from 'react'
import { municipalities } from '../listbox/data.ts'
import type { Municipality } from '../listbox/data.ts'
import { useComboboxTexts } from './texts.ts'
export function PlainFormCombobox() {
const { texts } = useComboboxTexts()
const [sent, setSent] = useState<string | undefined>()
return (
<form
onSubmit={(event) => {
// A real form sends the data from here.
event.preventDefault()
const value = new FormData(event.currentTarget).get('municipality')
setSent(typeof value === 'string' ? value : '')
}}
>
<Field.Root required>
<Field.Label>{texts.municipality}</Field.Label>
<Combobox.Root
items={municipalities}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
name="municipality"
defaultValue="goteborg"
>
<Combobox.Control>
<Combobox.Input />
<Combobox.Clear />
<Combobox.Toggle />
</Combobox.Control>
<Combobox.Popup>
<Combobox.List>
{(municipality: Municipality) => <Combobox.Option item={municipality} />}
</Combobox.List>
<Combobox.Empty />
</Combobox.Popup>
</Combobox.Root>
</Field.Root>
<Button type="submit" className="kv-button--primary">
{texts.send}
</Button>
{sent === undefined ? null : (
<p>
{texts.sent}: {sent}
</p>
)}
</form>
)
}Props in this example:
nameon Combobox.RootdefaultValueon Combobox.Root
Information: Did you know?
The text in the input is never sent, only the key of the chosen option. Pressing Enter with no active option submits the form, as in any text field.
A list of thousands
Let people filter first. If the list stays long after that, virtualize renders only the options in view plus the active and the chosen one. Each option tells a screen reader how many options there are and its place in the list. Options that are not drawn can’t be found with find in page or printed.
Type the first letters of the place.
import { Combobox, Field } from '@kvirn-ui/react'
import { places } from '../listbox/data.ts'
import type { Place } from '../listbox/data.ts'
import { useComboboxTexts } from './texts.ts'
export function LongListCombobox() {
const { texts } = useComboboxTexts()
return (
<Field.Root>
<Field.Label>{texts.place}</Field.Label>
<Field.Prose>
<p>{texts.placeHint}</p>
</Field.Prose>
<Combobox.Root
virtualize
items={places}
itemToString={(place) => place.name}
itemToKey={(place) => place.code}
>
<Combobox.Control>
<Combobox.Input />
<Combobox.Clear />
<Combobox.Toggle />
</Combobox.Control>
<Combobox.Popup>
<Combobox.List>{(place: Place) => <Combobox.Option item={place} />}</Combobox.List>
<Combobox.Empty />
</Combobox.Popup>
</Combobox.Root>
</Field.Root>
)
}Props in this example:
virtualizeon Combobox.Root
Accessibility#
What it does for you#
- Scope: Combobox, one or several choices from a list that the user filters by typing.
Combobox.RootwithCombobox.InputandCombobox.Popupis the editable combobox.Control,ToggleandClearare optional,ValueListandValueare formultiple. The popup parts (Popup,List,Option,Group,GroupLabel,Empty) are the Listbox's: their roles and styling are in listbox.a11y.md, andCombobox.Rootprovides the same context. Autocomplete (free text) has its own contract: autocomplete.a11y.md. - 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 option is active until an arrow key, arrows don't wrap, Page Up and Page Down move ten options, Home, End, ArrowLeft and ArrowRight stay with the text field and return visual focus to it (no option stays active), Tab closes the popup without choosing, a second Escape doesn't clear the text, and there is no inline completion (
aria-autocomplete="list", not"both"). The optional Toggle and Clear buttons are not tab stops, which is allowed because the keyboard has other ways to do the same (see Keyboard). - Native elements used:
<input type="text" role="combobox">(Input),<div popover="manual">(Popup),<div role="listbox">(List),<div role="option">,<div role="group">,<ul>and<li>(ValueList, Value),<button type="button">(Toggle, Clear, and each remove button),<input type="hidden">(the plain-form value).
A Combobox is for choosing from a list that is too long to scan: the user types a few letters, the list shrinks, and they choose. The value is one of the options (or several), never the text: text that matches nothing stays in the field and the value is null, so your validation can say "Choose an option in the list". The value is the chosen option's key (itemToKey), never copied into KvirnUI state: value, onValueChange and inputValue, onInputValueChange are yours, or defaultValue and name for a plain <form>. The text is never cleared or replaced silently: only choosing an option replaces it (with the option's text, or with an empty field in multiple, because the choice moves to the value list), and only the Clear button empties it.
| Part | Element / role | ARIA / state | Notes |
|---|---|---|---|
| Combobox.Root | none | none | Owns items or groups, itemToString, itemToKey, isItemDisabled, filter, isLoading, multiple, value / defaultValue / onValueChange(value, { reason }), inputValue / defaultInputValue / onInputValueChange(text, { reason }), name, disabled, id, open / defaultOpen / onOpenChange(open, { reason }), placement, offset, padding, announcementDebounceMilliseconds, messages. Hidden inputs for a plain form come after the children |
| Combobox.Control | <div>, no role. Optional | data-open, data-focus-visible, data-invalid, data-disabled | Class kv-combobox-control. The box around the input and its Toggle and Clear. The popup is placed against it (as wide as it) instead of against the input alone. The default theme draws the field's edge and focus ring on it |
| Combobox.Input | <input type="text" role="combobox"> | aria-autocomplete="list", aria-expanded, aria-controls (the List), aria-activedescendant (only while open, and only to a rendered option), aria-describedby, aria-invalid="true", aria-required="true". Native disabled. data-open, data-focused, data-focus-visible | Class kv-combobox-input. Named by the Field's <label for>. DOM focus stays on it. autocomplete="off" unless you set your own, so the browser's list doesn't compete with ours, and spellcheck="false". A click on it doesn't open the popup. Without a Field give it aria-label or aria-labelledby |
| Combobox.Popup | <div popover="manual">, no role, always rendered | data-open, data-placement, data-loading | Shared with the Listbox: class kv-listbox-popup. The shell: edge, shadow and position. In the top layer, hidden by the browser while closed. As wide as the input (or Control), flips, and is never taller than the room that is left. A press in it never takes focus from the input. Holds the List and, beside it, the Empty text |
| Combobox.List | <div role="listbox">, always in the DOM | aria-multiselectable="true" with multiple, aria-labelledby (the Field's label), or your aria-label on the List. hidden and data-empty while the popup is open with no option | Shared: class kv-listbox-list. The element that aria-controls points at, and the one that scrolls (overflow-y: auto), so axe treats it as a combobox popup and asks for no tab stop. Renders one Option per item (or per group) only while the popup is open, and only the items that the filter lets through |
| Combobox.Option | <div role="option"> | aria-selected="true" | "false", aria-disabled="true" when disabled. data-active, data-selected, data-disabled. id for aria-activedescendant | Shared. aria-selected means chosen, not highlighted. In a Combobox of one choice the chosen option is selected, and in multiple every chosen option |
| Combobox.Group | <div role="group"> | aria-labelledby (the label's id) | Shared, with Combobox.GroupLabel. A group left with no match is not rendered |
| Combobox.Empty | <div>, plain text, no role | none | Shared. Shown while the popup is open and no option matches, beside the hidden List, never inside the listbox. Default text combobox.noResults, or combobox.loading while isLoading. Not an option: no screen reader reads it as "option 1 of 1". Not announced by itself |
| Combobox.Toggle | <button type="button" tabindex="-1">. Optional | aria-label (combobox.showOptions), aria-expanded, aria-controls (the List), native disabled. data-open | Class kv-combobox-toggle. Opens and closes the popup. Not a tab stop. A press keeps focus on the input. No children: the theme draws a chevron |
| Combobox.Clear | <button type="button" tabindex="-1">. Optional | aria-label (combobox.clear), native disabled | Class kv-combobox-clear. One choice: empties the text and the value. Several choices: empties the typed text only, and every chosen value stays until its own remove button is pressed (one press never throws away a whole selection). Focus stays on (or goes to) the input. Rendered only while there is something to clear: text, or with one choice a value. Not a tab stop |
| Combobox.ValueList | <ul role="list">, multiple. Renders nothing while no value is chosen | aria-labelledby (the Field's label), or your aria-label | Classes kv-tag-group-list (Tag's), with kv-combobox-value-list kept as an alias for one minor version. The role="list" is redundant on purpose: Safari drops the list semantics when the theme removes the markers. Goes before the input, so the chosen values come first. "Kommuner, list, 2 items" |
| Combobox.Value | <li> holding one <button type="button"> that is the whole chip: the text and a cross | the remove button's aria-label is combobox.removeValue with the item's text (itemToString, "Remove Stockholm" in English). Custom children must show that text (2.5.3); a dev warning fires if a string does not | Classes kv-tag and kv-tag-remove (Tag's), with kv-combobox-value, kv-combobox-value-label and kv-combobox-value-remove kept as aliases for one minor version. The text is inside the button, so pressing it removes the value, the same as the cross. The cross is drawn by the theme (kv-tag-remove-icon). It is a tab stop, in DOM order before the input. removeIcon replaces the cross |
| Hidden input | <input type="hidden" name value> | none | One per chosen key with name, so a plain <form> and FormData work. A single choice sends '' when nothing is chosen. None when disabled. The visible text is never sent, because it is not the value |
| Field.Label | <label for> (the input's id) | the whole label is the click target, and a click focuses the input | "(optional)" in English, unless the Field is required or marker="none" |
useCombobox | the same attributes, for your own elements | controlProps, inputProps, toggleProps, clearProps, valueListProps, getValueProps(value), getRemoveButtonProps(value), popupProps, listProps, emptyProps, getOptionProps(entry), getGroupProps, getGroupLabelProps, hiddenInputs, entries, sections, selectedValues, isOpen, inputValue | Options as the Root. Reads the nearest Field. The refs are in the props: mergeProps merges yours |
Rules, tested in combobox.test.tsx:
- ARIA 1.2 combobox, not 1.0 or 1.1.
role="combobox"is on the input, witharia-expanded,aria-controlsandaria-autocomplete="list"; theListinside the popup is thelistboxthataria-controlspoints at; the options areoptions (combobox.test.tsx › a closed combobox: a native input wired to a hidden listbox popup). The List is always in the DOM, soaria-controlspoints at an element on every render. With no option to show it ishiddenand the input reportsaria-expanded="false"(nothing to move into, as in the APG), while the popup may still show the Empty text. Options render only while it is open. - Named by its label, described by its help text and error. The help text is a
Field.Prosein the Field: its description is its text content, so keep it short and plain. (combobox.test.tsx › the Field’s label names the input, and the help text describes it,combobox.test.tsx › invalid, required and disabled come from the Field). A dev warning fires when an input in a Field has no Field.Label, or has no name at all (1.3.1, 4.1.2). aria-activedescendantalways points at a rendered option, and is absent while closed and until the user moves. Typing clears it, so it never points at an option the filter has taken away (combobox.test.tsx › aria-activedescendant always points at a rendered option, and typing clears it). Opening by typing or by a press activates nothing, so Enter never chooses something the user didn't move to.- Focus never leaves the input. Typing, opening, choosing, a click on an option, a press in the popup and a press on Toggle or Clear keep it there (
combobox.test.tsx › a press inside the popup keeps focus on the input). The remove buttons are the one exception, because they are focusable buttons the user chose to press. - The text is never cleared silently. Text that matches no option stays after Tab, Escape and a blur, and the value is
null(combobox.test.tsx › text that matches no option stays after Tab and after Escape, and the value is null). Editing away from the chosen option's text makes the valuenulland keeps what was typed (combobox.test.tsx › editing away from the chosen text makes the value null, and keeps what was typed). - Enter keeps its native meaning when no option is active: the form can submit, and nothing is chosen (
combobox.test.tsx › Enter with no active option is the browser’s own: the form submits and nothing is chosen). A key during an IME composition belongs to the composition (combobox.test.tsx › a key during an IME composition is left to the composition). - Disabled options are reachable and cannot be chosen (
combobox.test.tsx › a disabled option can be reached with the arrow keys and cannot be chosen). - Filtering is on the label, anywhere in it, in the provider's locale: å, ä and ö are not a and o in Swedish, and accents are ignored where the locale allows (
combobox.test.tsx › å, ä and ö are not a and o in the Swedish provider). Your ownfilterreplaces it, andfilter={false}plusisLoadingserves results that the server has filtered. - Multiple.
aria-multiselectable="true", a choice adds a value, empties the text and the popup stays open, and a chosen option chosen again takes the value away. Chosen values are a list of remove buttons before the input; removing one moves focus to the next remove button, else the previous one, else the input; Backspace in the empty input removes nothing (combobox.test.tsx › aria-multiselectable, and a choice adds a value, empties the text and keeps the popup open,combobox.test.tsx › removing a value moves focus to the next remove button,combobox.test.tsx › removing the last value moves focus to the previous remove button,combobox.test.tsx › removing the only value moves focus to the input,combobox.test.tsx › Backspace in the empty input does not remove a value). - No form state. The value and the text are controlled with
valueandinputValue, or uncontrolled withdefaultValueanddefaultInputValue. A controlled value or text that the parent doesn't update stays as it is (combobox.test.tsx › controlled: stays as it is when the parent does not update the value,combobox.test.tsx › controlled inputValue: shows the text it is given, and a refused change is pulled back). Withname, hidden inputs carry the value (combobox.test.tsx › with a name, a hidden input carries the chosen key in a plain form, and the typed text is not sent). - Server rendering. The server writes the input, a closed popup, the hidden inputs and no options (
combobox.test.tsx › the server markup has the input, a closed popup and a hidden input, and no options). - Every part merges the consumer's class, handlers and refs with its own. For another element, spread the
useComboboxprop objects on your own. - Dev warnings: a part outside a Root, an input without a name, a
Combobox.Valuefor an item that is not chosen, an option whose item is not in the list, noKvirnProviderwhen something has to be announced,virtualizewithgroups, andvirtualizewith aCombobox.Listwhose children aren't a function.
What you need to do#
- A
Field.Labelwith a visible question, always. A placeholder is not a label. Outside a Field, give the inputaria-labeloraria-labelledby, and theCombobox.Listaria-labelwhen its name should differ. - Pass
items(orgroups) and give each item a stableitemToKey. A newitemsarray refreshes the list: pass one whenisItemDisabled,itemToStringoritemToKeychange meaning, and memoize it when you build it in render. For server filtering passfilter={false},isLoading, and your own debounce and fetch. autoCompletedefaults tooff. A field for the user's own data (for example their town) needs the rightautoCompletetoken, such asaddress-level2, for 1.3.5 Identify Input Purpose.- Validate and set
invalidyourself, with a Field.ErrorMessage that says what to do ("Choose an option in the list"). Text that matches no option leaves the valuenull: the Combobox never clears it for you. Don't change the page, submit or move focus when the value changes (3.2.2). - Keep the list in a meaningful order. For up to about 15 options use a Listbox or a RadioGroup instead, and for free text with suggestions use Autocomplete.
- A rich option (an icon, a description) must still have a plain text name, which is also what goes in the input when it is chosen.
- Apply
onValueChange(null, { reason: 'input' }): it is what "the text no longer names the chosen option" reports. A controlled parent that keeps the old value gets the chosen option's text put back, which would undo what the user is typing. - Pass
valueandonValueChange(andinputValuewithonInputValueChangeif you control the text, set to the chosen option's text while a value is chosen), ordefaultValueandnamefor a plain<form>. - Put
Combobox.ToggleandCombobox.Clearinside aCombobox.Control, after the input, if you want them. Don't make them tab stops. - For thousands of options, let the user filter first, and use
virtualizeonly for what stays long. GiveCombobox.Lista height limit andoverflow-y: auto(the default theme does), render it with a function child, and don't usegroups: 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#
- Focus indicator: on keyboard focus, a ring at least 2px thick, set off from the element, with at least 3:1 contrast against the adjacent colours, around the input (or around the Control, which draws the edge) (2.4.7 Focus Visible, level AA; 2.4.13 Focus Appearance, level AAA). The input has
data-focusedwhile it has focus, anddata-focus-visible(also set on the Control) for any focus, unless a pointer moved it there. Browsers also match:focus-visibleon a click in a text input, so the ring followsdata-focus-visible, or:focus-visiblealone before the script runs. A click shows focus as a 2px edge in the focus colour, with no ring, so it changes width as well as colour. The text doesn't move. Focused and invalid keeps the thick error edge, and the ring shows on any focus, a click included (form-fields.md §6.8a). The active option is shown by a bar at its start and a tinted fill, never by colour alone; the chosen option by a tick (1.4.1, 2.4.7). The popup's look is the Listbox's. - Target size: the input, each option, Toggle, Clear and each chip are at least 24 × 24 CSS px, even where the drawn mark is smaller, and taller in the default theme (2.5.8). Each chip is one button.
- Colour: the same look as the TextInput. An edge you can see, a thicker edge when invalid and a dashed edge when disabled, so state is not shown by colour alone. The chosen values are chips with an edge, so they are not told apart from the page by colour alone.
- forced-colors behaviour (Windows contrast themes): the system's colours. Edges use the button-text colour. An invalid field has a thicker edge, and a disabled one a dashed edge in the disabled-text colour. Focus in the input turns the edge to the highlight colour, and keyboard focus draws a highlight ring. On a standalone input, the system paints an outline on a click, so a click shows a ring there too. Inside a Control the input has no outline of its own, so a click shows only the thin highlight edge (a known limit). The active option uses the highlight colours, and the cross and chevron take the text colour.
- reduced-motion behaviour: nothing moves. The popup does not animate its position or opacity, and the edge and fill change with a transition only when motion is allowed.
- Reflow: the input is as wide as its column and no wider, the popup is at least as wide as it and never wider than the viewport, the chips wrap, and long option text wraps.
- RTL: the text, the chips and the chevron follow the reading direction, and the tick is at the inline end.
Focus management#
- Initial focus: not moved. Opening never moves DOM focus (a keyboard user stays in the text field), and no option is active until ArrowDown or ArrowUp, except that opening with a key activates the chosen option 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: it closes the popup without choosing and moves on (2.1.2). - Restore to: the input, which never lost focus. Escape, a press on an option, Toggle and Clear keep it there. After a value is removed, focus goes to the next remove button, else the previous one, else the input, so it is never lost to the page. A press outside leaves focus where the press put it (a control that was pressed keeps 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). Its height is limited to the room that is left, and it scrolls inside. The active option is scrolled into view when a key moves it, so it is never out of sight.
Virtualization#
virtualize is off by default. It renders only the options that are scrolled into view, for a flat list of thousands. A Combobox filters as the user types, so the list is often short: virtualize a list that stays long after filtering. The rules below are enforced in one place, createListVirtualizer in @kvirn-ui/core, and the same tests cover Listbox, Combobox and Autocomplete. They are written out in full in listbox.a11y.md › Virtualization; here is what they mean for an input that keeps DOM focus.
- Keep what matters mounted. The active option and every chosen option are always rendered, even when they are scrolled out of view, so
aria-activedescendanton the input never points at nothing (4.1.2;combobox-virtual.test.tsx › virtualized: ArrowDown and ArrowUp always leave aria-activedescendant on an option in the page). - Scroll before you point. A key that moves the active option scrolls to it, and the option is rendered in the same commit that sets
aria-activedescendant(2.4.3, 2.4.7;combobox-virtual.test.tsx › virtualized: ArrowUp opens the popup and activates the last option, rendered and in view). A pointer move doesn't scroll. Opening with a key scrolls to the chosen option. - Navigate the data, not the DOM. The arrows and Page Up and Page Down move through the whole filtered list (2.1.1;
combobox-virtual.test.tsx › virtualized: PageDown and PageUp move ten options that may not be rendered). Home and End still move the caret in the text field, as in any input, and don't move through the list. - Expose the full size. Every rendered option has
aria-setsize(the number of options after filtering) andaria-posinset(its place, from 1), so the size follows each keystroke (1.3.1;combobox-virtual.test.tsx › 10 000 items mount only a window of options, each with its place in the whole list,combobox-virtual.test.tsx › typing a text that few options contain renders them all, and the window follows the list). The result count that is announced is the filtered count, not the number of rendered options. - The list is the scroll element, with one sizer element inside it (
kv-listbox-virtual-sizer) and absolutely positioned options. The geometry is inline and nothing else: the library ships no CSS. The list carriesdata-virtualized, and must be a scroll container with a height limit (the default theme makes it one). - Flat lists only. With
groups,virtualizeis ignored and a development warning is logged. The list renders in full. - Off by default, and the docs say why. Options that aren't rendered can't be found with find in page, aren't printed, and are out of reach of a screen reader's browse mode.
- Screen-reader support varies.
aria-setsize,aria-posinsetandaria-activedescendantinto a virtualized list are read differently by NVDA, JAWS, VoiceOver and TalkBack. Test it with the screen readers your users have.
Rich options#
An option holds any markup. Combobox.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, the label,
aria-expanded,aria-controls,aria-activedescendant,aria-selected,aria-disabled,aria-multiselectable, the value list and the remove buttons' names. - 1.4.1 Use of Color (A), 1.4.11 Non-text Contrast (AA): the edge, the invalid width, the active bar, the tick and the chips.
- 1.4.10 Reflow (AA): the 320px popup and chips. 1.4.13 Content on Hover or Focus 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) and 3.2.2 On Input (A): the APG keys, one Tab stop, no context change when choosing, filtering or typing.
- 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 chips' names and the size of every control.
- 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, and text that is kept instead of cleared. Nothing the user typed is lost. 1.3.5 Identify Input Purpose (AA):
autoCompletewhere the input is for a known purpose (address-level2). - 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 option is
aria-activedescendant - Selection follows focus
- no (Enter, Alt+ArrowUp or a click chooses an option, and the arrow keys only move the highlight)
- Arrows wrap
- no
- Shortcuts
- none
The input is one Tab stop. In multiple the remove buttons come before it in the Tab order. Toggle and Clear are not tab stops (tabindex="-1"), because everything they do has a key: ArrowDown and Alt+ArrowDown open the popup, and the text can be selected and deleted. They are still in the accessibility tree, so touch screen reader users and voice control reach them by name. Home, End, ArrowLeft, ArrowRight (with or without Shift or Control) and Space are the text field's own: the caret moves and a space is typed, and they are never cancelled. The four caret keys also return visual focus to the field, as the APG says: the active option 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 (F5, Control+L), and Control and Command combinations are never taken.
| Key | Where | What happens |
|---|---|---|
| Tab | before the field | Moves focus to the input. One stop. With several choices the remove buttons come first Test: combobox.test.tsx › Tab goes through the field in order: the input is one stop |
| Shift+Tab | on the input, popup closed | Moves focus to the previous focusable element Test: combobox.test.tsx › Shift+Tab leaves the input backwards while the popup is closed |
| Tab | disabled input | Skips it (native disabled)Test: combobox.test.tsx › a disabled combobox does not open, and is not focusable |
| Tab | several choices, values chosen | Moves through the remove buttons in order, then to the input Test: combobox.test.tsx › a remove button is operated with Enter and Space, and Tab reaches it before the input |
| any character | on the input | Typed into the input: the list is filtered to what contains the text, and the popup opens. Nothing is active, and nothing is announced until typing stops Test: combobox.test.tsx › typing opens the popup with the matching options, and focus stays on the input |
| any character | on the input, Swedish | Filtering keeps å, ä and ö apart from a and o Test: combobox.test.tsx › å, ä and ö are not a and o in the Swedish provider |
| ArrowDown | on the input, popup closed | Opens the popup and activates the chosen option, or the first. Focus stays on the input Test: combobox.test.tsx › ArrowDown on the closed input opens it and activates the first option |
| ArrowUp | on the input, popup closed | Opens the popup and activates the chosen option, or the last Test: combobox.test.tsx › ArrowUp on the closed input opens it and activates the last option |
| ArrowDown | popup open | Activates the next option, and scrolls it into view. Stops at the last option Test: combobox.test.tsx › ArrowDown and ArrowUp move the active option and stop at the ends: no wrap |
| ArrowUp | popup open | Activates the previous option. Stops at the first option Test: combobox.test.tsx › ArrowDown and ArrowUp move the active option and stop at the ends: no wrap |
| PageDown / PageUp | popup open | Moves the active option ten on or back, and stops at the last or the first Test: combobox.test.tsx › PageDown and PageUp move ten options, and stop at the ends |
| Home / End | on the input | Move the caret in the text, as in any input. Visual focus returns to the field: no option stays active and aria-activedescendant is removedTest: combobox.test.tsx › Home, End, ArrowLeft, ArrowRight and Space are left to the input: the caret moves, a space is typed, and no option stays active |
| ArrowLeft / ArrowRight | on the input | Move the caret, as in any input, and leave no option active. In right-to-left text they still only move the caret Test: combobox.test.tsx › Home, End, ArrowLeft, ArrowRight and Space are left to the input: the caret moves, a space is typed, and no option stays active |
| ArrowDown / ArrowUp | popup open, right to left | Still the next and the previous option: vertical arrows don't flip. ArrowLeft and ArrowRight only move the caret Test: combobox.test.tsx › right to left: ArrowDown and ArrowUp still mean next and previous option, and ArrowLeft and ArrowRight only move the caret |
| ArrowUp | on the closed input, virtualized | Opens the popup and activates the last option of the whole list, although it isn't rendered. It is rendered and scrolled into view, and aria-activedescendant points at itTest: combobox-virtual.test.tsx › virtualized: ArrowUp opens the popup and activates the last option, rendered and in view |
| ArrowDown / ArrowUp | popup open, virtualized | Moves to the next or the previous option of the whole list. Each is rendered before aria-activedescendant points at it, so the id always resolves to an element in the pageTest: combobox-virtual.test.tsx › virtualized: ArrowDown and ArrowUp always leave aria-activedescendant on an option in the page |
| PageDown / PageUp | popup open, virtualized | Moves the active option 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: combobox-virtual.test.tsx › virtualized: PageDown and PageUp move ten options that may not be rendered |
| any character | on the input, virtualized | Filters the whole list, not only the options that are rendered. The smaller list is still virtualized, and aria-setsize is the number that is leftTest: combobox-virtual.test.tsx › typing a text that few options contain renders them all, and the window follows the list |
| Enter | popup open, an option is active | Chooses it. One choice: its text goes in the input and the popup closes. Several: it is added to the value list, the text is emptied and the popup stays open. Focus stays Test: combobox.test.tsx › Enter chooses the active option, puts its text in the input and closes the popup |
| Enter | popup open, several choices, an option is active | Adds the option (or takes it away if it is chosen), empties the text, and the popup stays open so more can be chosen Test: combobox.test.tsx › aria-multiselectable, and a choice adds a value, empties the text and keeps the popup open |
| Enter | popup open and no option active, or popup closed | Nothing from us: the browser's own Enter, so a form submits what is there. Nothing is chosen Test: combobox.test.tsx › Enter with no active option is the browser’s own: the form submits and nothing is chosen |
| Space | on the input | Types a space. It never chooses an option Test: combobox.test.tsx › Home, End, ArrowLeft, ArrowRight and Space are left to the input: the caret moves, a space is typed, and no option stays active |
| Escape | popup open | Closes the popup. The text and the value stay, and focus stays on the input. A second Escape does nothing: losing typed text is worse than an extra key Test: combobox.test.tsx › Escape closes the popup and keeps the text and the value, and a second Escape keeps them too |
| Escape | popup closed | Nothing: the key is the page's own Test: combobox.test.tsx › Escape does nothing while the popup is closed |
| Alt+ArrowDown | on the input | Opens the popup without activating an option Test: combobox.test.tsx › Alt+ArrowDown opens the popup without activating an option |
| Alt+ArrowUp | popup open | Chooses the active option and closes the popup. With several choices it adds, and never takes a value away Test: combobox.test.tsx › Alt+ArrowUp chooses the active option and closes the popup |
| Tab | popup open | Closes the popup without choosing the active option, keeps the text, and moves focus to the next focusable element Test: combobox.test.tsx › Tab closes the popup without choosing the active option, and moves focus on |
| Shift+Tab | popup open | Closes the popup without choosing, keeps the text, and moves focus to the previous focusable element Test: combobox.test.tsx › Shift+Tab closes the popup without choosing, and moves focus back |
| ArrowDown / ArrowUp | popup open, a disabled option | The disabled option can be reached and is read as unavailable. Enter and a click don't choose it Test: combobox.test.tsx › a disabled option can be reached with the arrow keys and cannot be chosen |
| Backspace | empty input, several choices | Deletes nothing from the value list: only the remove buttons remove a value Test: combobox.test.tsx › Backspace in the empty input does not remove a value |
| Enter / Space | on a remove button | Removes the value. Focus moves to the next remove button, else the previous one, else the input Test: combobox.test.tsx › a remove button is operated with Enter and Space, and Tab reaches it before the input |
| Pointer press | on an option | Chooses it, and keeps focus on the input. A disabled option does nothing Test: combobox.test.tsx › a click on an option chooses it, closes the popup and keeps focus on the input |
| Pointer move | over an option | Makes it the active option Test: combobox.test.tsx › moving the pointer over an option makes it the active option |
| Pointer press | on Toggle | Opens the popup, or closes it when it is open. Focus stays on, or goes to, the input. Nothing is active Test: combobox.test.tsx › Toggle is a named button, not a tab stop, that opens and closes the popup and keeps focus on the input |
| Pointer press | on Clear | One choice: empties the text and the value. Several choices: empties the typed text only, the chosen values stay. Focus stays on, or goes to, the input Test: combobox.test.tsx › the Clear button empties the text and the value, and focus stays on the input |
| Pointer press | outside the popup, the input and its buttons | Closes the popup. A control that is pressed keeps the focus Test: combobox.test.tsx › a press outside closes the popup, and focus stays where the press put it |
| Pointer press | on the Field's label | Focuses the input and opens nothing Test: combobox.test.tsx › clicking the label focuses the input |
Announcements#
Combobox tells screen reader users about these changes without moving focus. Each message waits until the screen reader is quiet (polite) or interrupts it (assertive).
| When | What it says | Message key | Politeness |
|---|---|---|---|
| The popup is open and the list has N options | combobox.resultCount | Polite | |
| The popup is open and no option matches | combobox.noResults | Polite | |
| The popup is open and the options are loading | combobox.loading | Polite |
The text in all five languages
Change the text#
For your whole app, pass messages to KvirnProvider. For one Combobox, 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 { Combobox, useCombobox } from '@kvirn-ui/react'Combobox.Root
Renders no element of its own. It renders hidden inputs after its children when you give name. Put a Combobox.Input and a Combobox.Popup inside it, in a Field, the popup right after the input.
| Prop | Type | Default | Description |
|---|---|---|---|
items | readonly 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. |
groups | readonly { key: string; label: string; items: readonly TItem[] }[] | – | Items in named groups, instead of items. Groups do not nest. |
itemToString | (item: TItem) => string | String(item) | The text of an item: shown in the list, matched by the filter, and put in the input when it is chosen. |
itemToKey | (item: TItem) => string | itemToString | A stable, unique key for an item. The value holds keys, not items. |
isItemDisabled | (item: TItem) => boolean | – | A disabled option stays reachable with the arrow keys and cannot be chosen. |
filter | ((item: TItem, query: string) => boolean) | false | Matches the query anywhere in the text | Replaces 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. |
isLoading | boolean | false | The options are being fetched. The popup shows and announces “loading”, and sets data-loading. items may still hold the last result. |
multiple | boolean | false | Several choices. Chosen values go into a list before the input, and the popup stays open after a choice. |
value | string | null, or readonly string[] with multiple | – | Controlled: the chosen key, or the chosen keys. null means nothing is chosen. |
defaultValue | string | null, or readonly string[] with multiple | – | Uncontrolled: the key or keys chosen to begin with. |
onValueChange | (value, { reason: 'option-press' | 'key' | 'input' | 'remove' | 'clear' }) => void | – | Called with the chosen key (an array with multiple). It is called with null when the text no longer names the chosen option (input). It only reports: apply it when value is controlled. |
name | string | – | A hidden input per chosen key for a plain form. The text in the input is never sent. |
inputValue | string | – | Controlled: the text in the input. Give the chosen option’s text while a value is chosen. |
defaultInputValue | string | The chosen option’s text | Uncontrolled: the text to begin with. |
onInputValueChange | (inputValue: string, { reason: 'input' | 'selection' | 'clear' }) => void | – | Called with the text when the user types, chooses an option (it fills or empties the text) or clears. It only reports. |
disabled | boolean | false | Disables it. A disabled Field disables it too. |
id | string | – | The input’s id, outside a Field. Inside one, the Field’s id is used. |
open | boolean | – | Controlled: whether the popup is open. Pair it with onOpenChange. |
defaultOpen | boolean | false | Uncontrolled: 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. |
placement | Placement | 'bottom-start' | Where the popup goes when there is room. It flips when it does not fit. |
offset | number | 4 | The gap between the field and the popup, in pixels. |
padding | number | 8 | The space kept to the edge of the viewport, in pixels. |
announceResults | boolean | true | Whether 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. |
announcementDebounceMilliseconds | number | 500 | How long to wait after the last change before the result count is announced. Nothing is announced while the user types. |
messages | Partial<KvirnMessages['combobox']> | – | Per-instance text: the result count, “no results”, “loading” and the names of the buttons. |
virtualize | boolean | { estimateSize?: number; overscan?: number } | false | Renders 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. |
Combobox.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 attribute | Values | Meaning |
|---|---|---|
kv-combobox-control | always | The part class. The default theme draws the field’s edge on it. |
data-open | present or absent | The popup is open. |
data-focus-visible | present or absent | The input has keyboard focus (:focus-visible). |
data-invalid | present or absent | The Field is invalid. |
data-required | present or absent | The Field is required. |
data-disabled | present or absent | The Combobox is disabled. |
Combobox.Input
Renders <input type="text" role="combobox" aria-autocomplete="list">, named by the Field’s label. Focus stays on it, and the active option is aria-activedescendant. Its autoComplete is off unless you set your own.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-combobox-input | always | The part class. |
data-open | present or absent | The popup is open. |
data-focused | present or absent | The input has focus, however it got it. |
data-focus-visible | present or absent | The input has keyboard focus (:focus-visible). |
data-invalid | present or absent | The Field is invalid. |
data-required | present or absent | The Field is required. |
data-disabled | present or absent | The Combobox is disabled. |
Combobox.Toggle
Renders <button type="button" tabindex="-1"> that opens and closes the popup, named “Show options” (combobox.showOptions). It is optional, not a tab stop, and a press keeps focus in the input. Put it after the input, in a Combobox.Control.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-combobox-toggle | always | The part class. The default theme draws a chevron. |
data-open | present or absent | The popup is open. |
data-disabled | present or absent | The Toggle is disabled. |
Combobox.Clear
Renders <button type="button" tabindex="-1"> named “Clear” (combobox.clear). With one choice it empties the text and the value. With multiple it empties the typed text only, and the chosen values stay. It renders only while there is something to clear.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-combobox-clear | always | The part class. |
data-disabled | present or absent | The Clear button is disabled. |
Combobox.ValueList
Renders <ul role="list"> of the chosen values, for multiple, before the input and named by the Field’s label. It renders nothing while no value is chosen.
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | (item: TItem, value: ComboboxSelectedValue<TItem>) => ReactNode | One Combobox.Value per chosen value | A function that renders one Combobox.Value per chosen value. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-tag-group-list | always | The part class. kv-combobox-value-list stays as an alias for one minor version. |
Combobox.Value
Renders <li> with one <button> that holds the value’s text and a cross. It is named “Remove …” (combobox.removeValue), and pressing it removes the value. The button is a normal tab stop. Removing a value moves focus to the next remove button, else the previous, else the input.
| Prop | Type | Default | Description |
|---|---|---|---|
item | TItem | Required | One of the chosen items, as ValueList hands it to you, unchanged. |
children | ReactNode | The item’s text | The visible text. The remove button’s name uses the item’s text (itemToString), so these children must show it (2.5.3). |
removeIcon | ReactNode | A cross drawn by the theme | Replaces the cross at the end of the chip, inside the remove button. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-tag | always | The part class on the <li>. kv-combobox-value stays as an alias for one minor version. |
kv-combobox-value-label | always | The class of the text inside the button (an alias, no styles). |
kv-tag-remove | always | The class of the button inside it, the whole chip. kv-combobox-value-remove stays as an alias for one minor version. |
data-disabled | present or absent | The Combobox is disabled. |
Combobox.Popup
Renders <div popover="manual"> with no role, in the top layer: the same part as Listbox.Popup. Focus never enters it.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-popup | always | The part class. Combobox and Autocomplete keep it. |
data-open | present or absent | The popup is open. |
data-placement | a placement, such as bottom-start | The side the popup is on now, after it flipped. |
data-detached | present or absent | The anchor is scrolled out of view, so the popup is hidden. |
data-loading | present or absent | The popup is open and isLoading is on. |
Combobox.List
Renders <div role="listbox"> inside the popup: the same part as Listbox.List. It has aria-multiselectable with multiple.
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | (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 attribute | Values | Meaning |
|---|---|---|
kv-listbox-list | always | The part class. This is the part that scrolls. |
data-empty | present or absent | The popup is open and there is no option, so the list is hidden. |
data-virtualized | present or absent | Only some options are rendered. |
kv-listbox-virtual-sizer | always | Inside a virtualized list: one element with the height of the whole list. |
Combobox.Option
Renders <div role="option">: the same part as Listbox.Option. aria-selected means chosen, not highlighted.
| Prop | Type | Default | Description |
|---|---|---|---|
item | TItem | Required | One of the Root’s items, as List hands it to you. |
children | ReactNode | The item’s text | Your own content for a rich option. Its name is then its text content. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-option | always | The part class. |
lang | a language code, or absent | From itemToLang. |
data-active | present or absent | The option the arrow keys are on (aria-activedescendant). |
data-selected | present or absent | The option is chosen. |
data-disabled | present or absent | The option cannot be chosen. |
data-has-indicator | present or absent | The option holds an OptionIndicator. |
data-index | a number | In a virtualized list: the option’s place in the whole list. |
Combobox.OptionIcon
Renders <span aria-hidden="true">: the same part as Listbox.OptionIcon.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-option-icon | always | The part class. |
Combobox.OptionText
Renders <span> that names the option: the same part as Listbox.OptionText.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-option-text | always | The part class. |
Combobox.OptionDescription
Renders <span> that describes the option: the same part as Listbox.OptionDescription.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-option-description | always | The part class. |
Combobox.OptionIndicator
Renders <span aria-hidden="true">: the same part as Listbox.OptionIndicator.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-option-indicator | always | The part class. |
data-selected | present or absent | The option is chosen. |
Combobox.Group
Renders <div role="group">: the same part as Listbox.Group. A group left with no match is not rendered.
| Prop | Type | Default | Description |
|---|---|---|---|
section | ListboxSection<TItem> | Required | The group, as the Root hands it out. List passes it for you. |
children | ReactNode | (item: TItem, entry: ListboxEntry<TItem>) => ReactNode | – | A function renders the label, then one child per option. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-group | always | The part class. |
Combobox.GroupLabel
Renders <div> with the group’s name: the same part as Listbox.GroupLabel.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-group-label | always | The part class. |
Combobox.Empty
Renders <div> with plain text, shown while the popup is open and no option matches: the same part as Listbox.Empty. Its default text is “No results”, or “Loading results” while isLoading is on.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-empty | always | The part class. |
useCombobox
Options
| Prop | Type | Default | Description |
|---|---|---|---|
items | readonly 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. |
groups | readonly { key: string; label: string; items: readonly TItem[] }[] | – | Items in named groups, instead of items. Groups do not nest. |
itemToString | (item: TItem) => string | String(item) | The text of an item: shown in the list, matched by the filter, and put in the input when it is chosen. |
itemToKey | (item: TItem) => string | itemToString | A stable, unique key for an item. The value holds keys, not items. |
isItemDisabled | (item: TItem) => boolean | – | A disabled option stays reachable with the arrow keys and cannot be chosen. |
filter | ((item: TItem, query: string) => boolean) | false | Matches the query anywhere in the text | Replaces 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. |
isLoading | boolean | false | The options are being fetched. The popup shows and announces “loading”, and sets data-loading. items may still hold the last result. |
multiple | boolean | false | Several choices. Chosen values go into a list before the input, and the popup stays open after a choice. |
value | string | null, or readonly string[] with multiple | – | Controlled: the chosen key, or the chosen keys. null means nothing is chosen. |
defaultValue | string | null, or readonly string[] with multiple | – | Uncontrolled: the key or keys chosen to begin with. |
onValueChange | (value, { reason: 'option-press' | 'key' | 'input' | 'remove' | 'clear' }) => void | – | Called with the chosen key (an array with multiple). It is called with null when the text no longer names the chosen option (input). It only reports: apply it when value is controlled. |
name | string | – | A hidden input per chosen key for a plain form. The text in the input is never sent. |
inputValue | string | – | Controlled: the text in the input. Give the chosen option’s text while a value is chosen. |
defaultInputValue | string | The chosen option’s text | Uncontrolled: the text to begin with. |
onInputValueChange | (inputValue: string, { reason: 'input' | 'selection' | 'clear' }) => void | – | Called with the text when the user types, chooses an option (it fills or empties the text) or clears. It only reports. |
disabled | boolean | false | Disables it. A disabled Field disables it too. |
id | string | – | The input’s id, outside a Field. Inside one, the Field’s id is used. |
open | boolean | – | Controlled: whether the popup is open. Pair it with onOpenChange. |
defaultOpen | boolean | false | Uncontrolled: 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. |
placement | Placement | 'bottom-start' | Where the popup goes when there is room. It flips when it does not fit. |
offset | number | 4 | The gap between the field and the popup, in pixels. |
padding | number | 8 | The space kept to the edge of the viewport, in pixels. |
announceResults | boolean | true | Whether 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. |
announcementDebounceMilliseconds | number | 500 | How long to wait after the last change before the result count is announced. Nothing is announced while the user types. |
messages | Partial<KvirnMessages['combobox']> | – | Per-instance text: the result count, “no results”, “loading” and the names of the buttons. |
virtualize | boolean | { estimateSize?: number; overscan?: number } | false | Renders 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
| Prop | Type | Default | Description |
|---|---|---|---|
variant | 'combobox' | 'autocomplete' | – | Which of the two this is. |
isOpen | boolean | – | Whether the popup is open. |
isMultiple | boolean | – | Whether several can be chosen. |
isDisabled | boolean | – | From disabled or the Field. |
isInvalid | boolean | – | From the Field. |
isRequired | boolean | – | From the Field. |
isFocusVisible | boolean | – | Whether the input has keyboard (:focus-visible) focus. |
isLoading | boolean | – | Whether the options are loading. |
inputValue | string | – | What the input shows. |
hasClearableValue | boolean | – | There is text, or a chosen value (one choice only), so Clear has something to clear. |
entries | readonly ListboxEntry<TItem>[] | – | Every option the filter lets through, in order. index counts across groups. |
sections | readonly ListboxSection<TItem>[] | undefined | – | The groups with their entries, or undefined for a flat list. |
size | number | – | The number of options after filtering. |
activeKey | string | undefined | – | The active option’s key. Undefined while closed and until the user moves. |
selectedKeys | readonly string[] | – | The chosen keys. |
selectedValues | readonly ComboboxSelectedValue<TItem>[] | – | The chosen values in the order chosen, including ones the filter hides now. Each has key, item and label. |
emptyText | string | – | The text of Combobox.Empty unless you give it children: combobox.noResults. |
loadingText | string | – | The text of the loading state: combobox.loading. |
controlProps | ComboboxControlPartProps | – | Spread on the box around the input. It anchors the popup when present. |
inputProps | ComboboxInputPartProps | – | Spread on an <input>: role combobox, ARIA, value and handlers. |
toggleProps | ComboboxTogglePartProps | – | Spread on a <button> that opens and closes the popup. Not a tab stop. |
clearProps | ComboboxClearPartProps | – | Spread on a <button> that empties the text and the value. Not a tab stop. |
valueListProps | ComboboxValueListPartProps | – | Spread on the <ul> of the chosen values (multiple). |
getValueProps | (value: { key: string }) => ComboboxValuePartProps | – | The props of one chosen value’s <li>. |
getRemoveButtonProps | (value: ComboboxSelectedValue<TItem>) => ComboboxRemoveButtonPartProps | – | The props of a chosen value’s remove button. |
popupProps | ListboxPopupPartProps & { "data-loading"?: "" } | – | Spread on the popup: popover="manual", its id and ref. data-loading while loading. |
listProps | ListboxListPartProps | – | Spread on the role="listbox" element inside the popup. |
emptyProps | ListboxEmptyPartProps | – | 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. |
virtualization | ListboxVirtualization | undefined | – | Set while virtualize is on, the popup is open and the list is flat. |
readonly { name: string; value: string }[] | – | The hidden inputs of a plain form (Combobox only). |
Strings
These are the default texts in @kvirn-ui/i18n.
For your whole app, pass messages to KvirnProvider. For one Combobox, pass its messages prop.
combobox.resultCount
Announced, politely and after a pause, when the list changes because the user typed. The texts below use five results.
| Language | Default text |
|---|---|
| Svenska | 5 resultat |
| Suomi | 5 tulosta |
| Norsk bokmål | 5 treff |
| Norsk nynorsk | 5 treff |
| English | 5 results |
combobox.noResults
Announced when no option matches, and the default text of Combobox.Empty.
| Language | Default text |
|---|---|
| Svenska | Inga resultat |
| Suomi | Ei tuloksia |
| Norsk bokmål | Ingen treff |
| Norsk nynorsk | Ingen treff |
| English | No results |
combobox.loading
Announced while the options are loading, and the text of Combobox.Empty then.
| Language | Default text |
|---|---|
| Svenska | Laddar resultat |
| Suomi | Ladataan tuloksia |
| Norsk bokmål | Laster treff |
| Norsk nynorsk | Lastar treff |
| English | Loading results |
combobox.removeValue
The name of a remove button. The texts below use “Stockholm” as the value.
| Language | Default text |
|---|---|
| Svenska | Ta bort Stockholm |
| Suomi | Poista Stockholm |
| Norsk bokmål | Fjern Stockholm |
| Norsk nynorsk | Fjern Stockholm |
| English | Remove Stockholm |
combobox.clear
The name of the Clear button.
| Language | Default text |
|---|---|
| Svenska | Rensa |
| Suomi | Tyhjennä |
| Norsk bokmål | Tøm |
| Norsk nynorsk | Tøm |
| English | Clear |
combobox.showOptions
The name of the Toggle button.
| Language | Default text |
|---|---|
| Svenska | Visa alternativ |
| Suomi | Näytä vaihtoehdot |
| Norsk bokmål | Vis alternativer |
| Norsk nynorsk | Vis alternativ |
| English | Show options |
Known issues#
aria-activedescendanton VoiceOver and TalkBack has known gaps. A Combobox stays custom on touch devices (there is no native rendering), so test on iOS and Android with your users.- Toggle and Clear are not tab stops. That is allowed because their actions have keys (ArrowDown, Alt+ArrowDown, select and delete), and it keeps the Tab sequence short.
- Virtualization is opt-in and has limits. Without
virtualize, every matching option renders while the popup is open, so a list of many thousands is slow: usevirtualizefor those. With it, options that aren't rendered can't be found with find in page or printed, groups are not virtualized, andaria-activedescendantinto a virtualized list is unverified on VoiceOver and TalkBack (see Virtualization). - The popup has no tab stop. It scrolls natively, and keyboard users scroll it by moving the active option, which is scrolled into view.
- A Combobox inside a form with an Enter shortcut. Enter with an active option chooses it and never submits the form, as the pattern says. With no active option it submits (the browser's own). The text is not sent, only the hidden inputs are.
- Text that has no match is not an error by itself. The Combobox reports
nulland leaves the message to the consumer, because the right words depend on the form. - WebKit is not automated. Keyboard rows run in Vitest browser mode on Chromium. WebKit is not covered by the automated tests. 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 + OS | Agent check | Human check | Result | Notes |
|---|---|---|---|---|
| Automated (re-runnable tests) | ||||
| axe, WCAG 2.2 A and AA, every story, 4 themes | pass | n/a | pass | combobox.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | combobox.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) | pass | n/a | pass | 37 rows, each names a test in combobox.test.tsx |
| Focus order and management | pass | n/a | pass | combobox.test.tsx: typing opens the popup with the matching options, and focus stays on the input |
| Display modes (forced colours, 320px reflow, text spacing, reduced motion) | pass | n/a | pass | the four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI |
| Core (required for beta) | ||||
| NVDA + Chrome + Windows | pending | pending | pending | |
| VoiceOver + Safari + iOS | pending | pending | pending | |
| Release (before 1.0 and each minor) | ||||
| JAWS + Chrome + Windows | pending | pending | pending | |
| TalkBack + Chrome + Android | pending | pending | pending | |
| VoiceOver + Safari + macOS | pending | pending | pending |
Research questions for the AT run: is the result count read once, after typing stops, and not over the screen reader's own reading of the typed letter? Does the screen reader read the active option from aria-activedescendant on each arrow press, in NVDA, JAWS, VoiceOver (macOS and iOS) and TalkBack? Is the chosen text read after Enter? Is the value list's name and count useful, or noise, before the input? Does a Voice Control user say "show options" or "remove Stockholm" and reach the Toggle and the remove buttons?