When to use it#
- Use a Listbox when the user chooses one option, or a few, from a list they can scan, such as a municipality or a type of service.
- Keep the list short enough to scan. For more than about 15 options that people would search, use a Combobox. For free text with suggestions, use an Autocomplete.
- For a few choices that all fit on the page, radio buttons or checkboxes are easier to use than any list.
- For one choice on a touch device, the default
native="auto"shows the browser’s own select. The examples setnative="never"so you see the popup everywhere. See The browser’s own select. - Not for actions: use a Button for something that does, and a Link for going.
Example#
import { Field, Listbox } from '@kvirn-ui/react'
import { municipalities } from './data.ts'
import type { Municipality } from './data.ts'
import { useListboxTexts } from './texts.ts'
export function DefaultListbox() {
const { texts } = useListboxTexts()
return (
<Field.Root required>
<Field.Label>{texts.municipality}</Field.Label>
<Listbox.Root
native="never"
items={municipalities}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
placeholder={texts.municipalityPlaceholder}
>
<Listbox.Trigger />
<Listbox.Popup>
<Listbox.List>
{(municipality: Municipality) => <Listbox.Option item={municipality} />}
</Listbox.List>
<Listbox.Empty />
</Listbox.Popup>
</Listbox.Root>
</Field.Root>
)
}Use cases#
A required choice in a form
KvirnUI holds no form state. Give the Root a name and the chosen key goes into the form as a hidden input, so FormData and a plain submit work. With nothing chosen it sends an empty value: check for that yourself, say what to do, and move focus to the field.
import { Button, Field, Listbox } from '@kvirn-ui/react'
import { useEffect, useRef, useState } from 'react'
import { municipalities } from './data.ts'
import type { Municipality } from './data.ts'
import { useListboxTexts } from './texts.ts'
export function PlainFormListbox() {
const { texts } = useListboxTexts()
const [sent, setSent] = useState<string | undefined>()
const [isInvalid, setIsInvalid] = useState(false)
const [attempts, setAttempts] = useState(0)
const triggerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (isInvalid) {
triggerRef.current?.focus()
}
}, [isInvalid, attempts])
return (
<form
onSubmit={(event) => {
// A real form sends the data from here.
event.preventDefault()
const value = new FormData(event.currentTarget).get('municipality')
const hasChoice = typeof value === 'string' && value !== ''
setIsInvalid(!hasChoice)
setAttempts((count) => count + 1)
setSent(hasChoice ? value : undefined)
}}
>
<Field.Root required invalid={isInvalid}>
<Field.Label>{texts.municipality}</Field.Label>
<Listbox.Root
native="never"
items={municipalities}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
name="municipality"
placeholder={texts.municipalityPlaceholder}
onValueChange={() => setIsInvalid(false)}
>
<Listbox.Trigger ref={triggerRef} />
<Listbox.Popup>
<Listbox.List>
{(municipality: Municipality) => <Listbox.Option item={municipality} />}
</Listbox.List>
</Listbox.Popup>
</Listbox.Root>
<Field.ErrorMessage>{texts.chooseError}</Field.ErrorMessage>
</Field.Root>
<Button type="submit" className="kv-button--primary">
{texts.send}
</Button>
<output>{sent === undefined ? null : `${texts.sent}: ${sent}`}</output>
</form>
)
}Props in this example:
nameon Listbox.RootonValueChangeon Listbox.Root
Warning: Don't forget
Write the error as an instruction, “Choose a municipality”, and set invalid on the Field so the error is read with the field (3.3.1 Error Identification, 3.3.3 Error Suggestion). Don’t change the page or send the form when the value changes (3.2.2 On Input).
Options in groups
Use groups when the options fall into a few named sets that help people find one, such as regions. Each group has a visible label, and the same label names the group for a screen reader.
import { Field, Listbox } from '@kvirn-ui/react'
import { useMemo } from 'react'
import { findMunicipality } from './data.ts'
import type { Municipality } from './data.ts'
import { useListboxTexts } from './texts.ts'
export function GroupedListbox() {
const { texts } = useListboxTexts()
const groups = useMemo(
() => [
{
key: 'west',
label: texts.regionWest,
items: [findMunicipality('boras'), findMunicipality('goteborg')],
},
{
key: 'east',
label: texts.regionEast,
items: [findMunicipality('stockholm'), findMunicipality('uppsala')],
},
{
key: 'south',
label: texts.regionSouth,
items: [findMunicipality('lund'), findMunicipality('malmo')],
},
],
[texts],
)
return (
<Field.Root required>
<Field.Label>{texts.municipality}</Field.Label>
<Listbox.Root
native="never"
groups={groups}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
placeholder={texts.municipalityPlaceholder}
>
<Listbox.Trigger />
<Listbox.Popup>
<Listbox.List>
{(municipality: Municipality) => <Listbox.Option item={municipality} />}
</Listbox.List>
</Listbox.Popup>
</Listbox.Root>
</Field.Root>
)
}Props in this example:
groupson Listbox.Root
Choosing several options
Use multiple when the user may choose more than one. The popup stays open after a choice, each option toggles, and the value is an array of keys. The trigger shows the chosen texts joined by a comma.
import { Field, Listbox } from '@kvirn-ui/react'
import { municipalities } from './data.ts'
import type { Municipality } from './data.ts'
import { useListboxTexts } from './texts.ts'
export function SeveralListbox() {
const { texts } = useListboxTexts()
return (
<Field.Root>
<Field.Label>{texts.several}</Field.Label>
<Listbox.Root
native="never"
multiple
items={municipalities}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
defaultValue={['malmo', 'uppsala']}
placeholder={texts.severalPlaceholder}
>
<Listbox.Trigger />
<Listbox.Popup>
<Listbox.List>
{(municipality: Municipality) => <Listbox.Option item={municipality} />}
</Listbox.List>
</Listbox.Popup>
</Listbox.Root>
</Field.Root>
)
}Props in this example:
multipleon Listbox.RootdefaultValueon Listbox.Root
An option that cannot be chosen now
Some options are unavailable for a while. Keep them in the list so people know they exist, and say why in the text next to the field.
Stockholm is closed for new applications until 1 March.
import { Field, Listbox } from '@kvirn-ui/react'
import { municipalities } from './data.ts'
import type { Municipality } from './data.ts'
import { useListboxTexts } from './texts.ts'
export function DisabledOptionListbox() {
const { texts } = useListboxTexts()
return (
<Field.Root required>
<Field.Label>{texts.municipality}</Field.Label>
<Field.Prose>
<p>{texts.closedHint}</p>
</Field.Prose>
<Listbox.Root
native="never"
items={municipalities}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
isItemDisabled={(municipality) => municipality.code === 'stockholm'}
placeholder={texts.municipalityPlaceholder}
>
<Listbox.Trigger />
<Listbox.Popup>
<Listbox.List>
{(municipality: Municipality) => <Listbox.Option item={municipality} />}
</Listbox.List>
</Listbox.Popup>
</Listbox.Root>
</Field.Root>
)
}Props in this example:
isItemDisabledon Listbox.Root
Information: Did you know?
A disabled option stays reachable with the arrow keys, so a screen reader user hears that it exists. It can’t be chosen, and nothing says why unless you do.
The browser’s own select
On a phone the browser’s own select is often better than anything custom. native="always" renders one native select from the same items, with the same value, name and Field wiring. It shows plain text only. With the default native="auto", a touch device first draws the popup trigger and switches right after the page loads, so native="always" avoids that one frame.
import { Field, Listbox } from '@kvirn-ui/react'
import { municipalities } from './data.ts'
import { useListboxTexts } from './texts.ts'
export function NativeSelect() {
const { texts } = useListboxTexts()
return (
<Field.Root required>
<Field.Label>{texts.municipality}</Field.Label>
<Listbox.Root
native="always"
items={municipalities}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
placeholder={texts.municipalityPlaceholder}
name="municipality"
autoComplete="address-level2"
/>
</Field.Root>
)
}Props in this example:
nativeon Listbox.Rootplaceholderon Listbox.RootautoCompleteon Listbox.Root
Warning: Don't forget
Only the native select takes autoComplete. The popup trigger is not a form input, so a field that asks for the person’s own details needs native="always" to let the browser fill it in (1.3.5 Identify Input Purpose).
An icon and a second line in each option
An option can hold any markup. The optional parts give it a place and keep its name right: the icon is decorative, the text is the name, the description is read as help and the indicator marks the chosen one.
import { Field, Icon, Listbox } from '@kvirn-ui/react'
import { findMunicipality } from './data.ts'
import type { Municipality } from './data.ts'
import { useListboxTexts } from './texts.ts'
const richMunicipalities = [
findMunicipality('goteborg'),
findMunicipality('malmo'),
findMunicipality('stockholm'),
findMunicipality('uppsala'),
]
export function RichOptionsListbox() {
const { texts } = useListboxTexts()
return (
<Field.Root required>
<Field.Label>{texts.municipality}</Field.Label>
<Listbox.Root
native="never"
items={richMunicipalities}
itemToString={(municipality) => municipality.name}
itemToKey={(municipality) => municipality.code}
placeholder={texts.municipalityPlaceholder}
>
<Listbox.Trigger />
<Listbox.Popup>
<Listbox.List>
{(municipality: Municipality) => (
<Listbox.Option item={municipality}>
<Listbox.OptionIcon>
<Icon name="document" />
</Listbox.OptionIcon>
<Listbox.OptionText>{municipality.name}</Listbox.OptionText>
<Listbox.OptionDescription>{municipality.county}</Listbox.OptionDescription>
<Listbox.OptionIndicator />
</Listbox.Option>
)}
</Listbox.List>
</Listbox.Popup>
</Listbox.Root>
</Field.Root>
)
}Props in this example:
childrenon Listbox.Option
Warning: Don't forget
Every rich option still needs a plain text name, which is also its text in the trigger, and the native select shows text only. See What you need to do.
Choices in another language
Name each language in its own language, so people find theirs: Svenska (Swedish), Suomi (Finnish), English. A screen reader reads text in the voice of the page’s language unless the text says otherwise (3.1.2 Language of Parts), so give itemToLang the code of each item. It sets lang on each native option, each popup option and the chosen text in the trigger. Combobox and Autocomplete don’t support it: their value is an input, which has one lang for the whole text.
import { Field, Listbox } from '@kvirn-ui/react'
import { languages } from './data.ts'
import type { Language } from './data.ts'
import { useListboxTexts } from './texts.ts'
export function LanguageSwitcherListbox() {
const { texts } = useListboxTexts()
return (
<Field.Root>
<Field.Label>{texts.letterLanguage}</Field.Label>
<Listbox.Root
native="never"
items={languages}
itemToString={(language) => language.name}
itemToKey={(language) => language.code}
itemToLang={(language) => language.code}
defaultValue="sv"
>
<Listbox.Trigger />
<Listbox.Popup>
<Listbox.List>{(language: Language) => <Listbox.Option item={language} />}</Listbox.List>
</Listbox.Popup>
</Listbox.Root>
</Field.Root>
)
}Props in this example:
itemToLangon Listbox.RootitemToStringon Listbox.Root
Information: Did you know?
This chooses a setting in a form. To switch the language of the page itself, use links: a select that changes the page as soon as you choose can fail 3.2.2 On Input. In a form for residents, a few options usually work better as radio buttons.
A list of thousands
Filter or split a long list first. If it stays long, virtualize renders only the options in view, plus the active and the chosen one. Each option still 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.
import { Field, Listbox } from '@kvirn-ui/react'
import { places } from './data.ts'
import type { Place } from './data.ts'
import { useListboxTexts } from './texts.ts'
export function LongListListbox() {
const { texts } = useListboxTexts()
return (
<Field.Root>
<Field.Label>{texts.place}</Field.Label>
<Listbox.Root
native="never"
virtualize
items={places}
itemToString={(place) => place.name}
itemToKey={(place) => place.code}
placeholder={texts.placePlaceholder}
>
<Listbox.Trigger />
<Listbox.Popup>
<Listbox.List>{(place: Place) => <Listbox.Option item={place} />}</Listbox.List>
</Listbox.Popup>
</Listbox.Root>
</Field.Root>
)
}Props in this example:
virtualizeon Listbox.Root
Accessibility#
What it does for you#
- Scope: both renderings of Listbox.
Listbox.RootwithListbox.TriggerandListbox.Popupis the stylable rendering, the APG select-only combobox. The browser's own<select>is the other rendering, whichListbox.Rootrenders for a single choice on touch devices (native="auto", the default) and always fornative="always".native="never"keeps the popup. The popup parts (Popup,List,Option,Group,GroupLabel,Empty) are shared with Combobox and Autocomplete, which get their own contracts. - APG pattern: Combobox: Select-Only Combobox example for the popup, with Listbox for the popup's content. None for the native rendering: its role, keys and list come from the browser and the platform.
- Deviations: none from the APG keyboard practice. The choices are allowed by the pattern: arrows don't wrap, Page Up and Page Down move ten options, Tab chooses the active option and moves on. The trigger is a
<div role="combobox" tabindex="0">, as in the APG example. - Native elements used:
<div role="combobox" tabindex="0">(Trigger),<div popover="manual">(Popup, no role),<div role="listbox">(List),<div role="option">,<div role="group">,<input type="hidden">(the plain-form value), and for the native rendering<select>with<option>and<optgroup>, named by a<label for>(Field.Label).
A Listbox is one choice (or several) from a list, with no typing of text. On a desktop it is a stylable popup: it can hold groups and rich options, and the look is yours. On a phone, a single choice is the browser's own <select> with the platform's picker, which is better than anything custom. The value is the chosen option's key (itemToKey), never copied into KvirnUI state: value and onValueChange are yours, or defaultValue and name for a plain <form>. multiple always renders the popup, and so does any option with rich content: the native <select> shows one line of plain text per option.
| Part | Element / role | ARIA / state | Notes |
|---|---|---|---|
| Listbox.Root | none (popup rendering), or the native <select> | none | Owns items or groups, itemToString, itemToKey, isItemDisabled, value / defaultValue / onValueChange(value, { reason }), multiple, native, name, placeholder, autoComplete, disabled, id, open / defaultOpen / onOpenChange(open, { reason }), placement, offset, padding, messages. Hidden inputs for a plain form come after the children |
| Listbox.Trigger | <div role="combobox" tabindex="0"> | aria-expanded, aria-controls (the popup), aria-haspopup="listbox", aria-activedescendant (only while open, and only to a rendered option), aria-labelledby (the Field's label, then the value), aria-describedby, aria-invalid="true", aria-required="true", aria-disabled="true". data-open, data-focus-visible | Class kv-listbox-trigger. One Tab stop, and DOM focus stays on it. A tabIndex you pass wins over its own 0 (a Toolbar.Item sets the roving one; test: listbox-custom.test.tsx › a tabIndex from the consumer wins over the trigger’s own tabindex="0"). Disabled: no tabindex of its own, aria-disabled, data-disabled. A tabIndex you pass still applies while disabled, so a disabled Toolbar.Item keeps its roving one and stays reachable by the arrows (it doesn't open: toolbar.test.tsx › a Listbox disabled on its Root stays reachable by the arrows, is aria-disabled, and does not open). Outside a Field give it aria-label or aria-labelledby. Clicking the Field's label focuses it (<label for> doesn't name a <div>). The anchor the popup is placed against |
| Listbox.Value | <span> inside the trigger | none. data-placeholder while nothing is chosen. With itemToLang, each chosen label is a <span lang> (3.1.2 Language of Parts (AA)) | Class kv-listbox-value. The chosen options' texts joined by a comma, or placeholder. A function child gets the chosen items. Part of the trigger's name, and never its only label |
| Listbox.Popup | <div popover="manual">, no role, always rendered | data-open, data-placement | Class kv-listbox-popup. The shell: edge, shadow and position. In the top layer. Hidden by the browser while closed. As wide as the trigger, flips, and is never taller than the room that is left. A press in it never takes focus from the trigger (mousedown is cancelled). Holds the List and, beside it, the Empty text |
| Listbox.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 | Class kv-listbox-list. The element that aria-controls points at, and the one that scrolls, so it is not a tab stop of its own. Renders one Option per item (or per group) only while the popup is open. Function children: (item) => <Listbox.Option item={item} /> |
| Listbox.Option | <div role="option"> | aria-selected="true" | "false", aria-disabled="true" when disabled. data-active, data-selected, data-disabled. id for aria-activedescendant | Class kv-listbox-option. Children: the item's text, or your own rich content (the name is then its text content). A click chooses it. Moving the mouse over it makes it active |
| Listbox.Group, Listbox.GroupLabel | <div role="group">, and the <div> that names it | aria-labelledby (the label's id) | Classes kv-listbox-group, kv-listbox-group-label. Rendered by Listbox.List when the Root has groups. Flat: not nested |
| Listbox.Empty | <div>, plain text, no role, only while the popup is open and there are no options | none | Class kv-listbox-empty. Default text combobox.noResults. It sits in the popup beside the hidden List, never inside the listbox, and is not an option: no screen reader reads it as "option 1 of 1". Not announced |
| 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, and none in the native rendering (the <select> has the name) |
Language of an item (itemToLang) | lang on each <option> (native), each role="option" and the value's spans | lang only, no ARIA | A BCP 47 code from itemToLang(item), or none when it returns undefined (the page's language). Not on the empty native option, <optgroup>, the placeholder or the select. A lang of your own on an option wins. Tests: listbox-custom.test.tsx › itemToLang (3.1.2) |
| Native rendering | <select class="kv-listbox-native"> → combobox (single, no size), rendered by Listbox.Root | id and aria-describedby (description, then error), aria-invalid="true", aria-required="true" from the Field. Native disabled. data-invalid, data-required, data-disabled, data-focus-visible | An <option value=""> stands for "nothing chosen" and carries placeholder; it goes once something is chosen, unless a placeholder is set. The option values are the item keys. Disabled items are <option disabled>, groups are <optgroup>. name and autoComplete go on the select. Choosing the empty option reports null. Rich option content, Listbox.Empty and the popup's look don't apply. Not a public part: there is no Listbox.Native |
| Field.Label | <label for> (native) or the trigger's aria-labelledby target (popup) | the whole label is the click target (native), or focuses the trigger (popup) | the optional marker, "(optional)" in English (each language has its own), unless the Field is required or marker="none" |
useListbox | the same attributes, for your own elements | triggerProps, valueProps, popupProps, listProps, emptyProps, getOptionProps(entry), getGroupProps(section), getGroupLabelProps(section), hiddenInputs, entries, sections, selectedItems, isOpen, isNative, isMultiple, isDisabled, isInvalid, isRequired | Options as the Root. Reads the nearest Field |
Each rule below has a test, for the popup or for the native rendering:
- A combobox, not a select. The trigger is
role="combobox"witharia-expanded,aria-controlsandaria-haspopup="listbox"; theListinside the popup is thelistboxthataria-controlspoints at; the options areoptions (listbox-custom.test.tsx › a closed listbox: a combobox div wired to a hidden listbox popup). The popup and its List are always in the DOM, soaria-controlspoints at an element on every render. Options render only while it is open. - Named by its label and value, 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. (listbox-custom.test.tsx › the Field’s label and the value name the trigger, and the help text describes it,listbox-custom.test.tsx › invalid, required and disabled come from the Field). A dev warning fires when a trigger in a Field has no Field.Label, or has no name at all (1.3.1 Info and Relationships (A), 4.1.2 Name, Role, Value (A)). The native select is named by<label for>(listbox.test.tsx › the Field’s label is the name, and the description and error describe it). aria-activedescendantalways points at a rendered option, and is absent while closed and until the user moves (listbox-custom.test.tsx › aria-activedescendant always points at a rendered option). Opening with a press activates nothing, so Enter never chooses something the user did not move to.- Focus never leaves the trigger. Opening, choosing, a click on an option and a press in the popup keep it there (
listbox-custom.test.tsx › a press inside the popup keeps focus on the trigger). - Disabled options are reachable and cannot be chosen (
listbox-custom.test.tsx › a disabled option can be reached with the arrow keys and cannot be chosen). - Multiple.
aria-multiselectable="true", a choice toggles and the popup stays open, Tab closes without choosing (listbox-custom.test.tsx › aria-multiselectable, and a choice toggles the option and keeps the popup open). - No form state. The value is controlled with
valueandonValueChange, or uncontrolled withdefaultValue. A controlled value that the parent doesn't update stays as it is (listbox-custom.test.tsx › controlled: stays as it is when the parent does not update the value). Withname, hidden inputs carry it (listbox-custom.test.tsx › with a name, a hidden input carries the chosen key in a plain form). - Native rendering.
native="always"renders a<select>with the Field's label, help text and error,<optgroup>s for groups and the samename; the choice survives a switch of rendering and the popup is closed after it (listbox-custom.test.tsx › native="always" renders a native select with the Field’s label, description and error,listbox-custom.test.tsx › the choice survives a switch of rendering, and the popup is closed after it).multipleis never native (listbox-custom.test.tsx › multiple always renders the popup, and native="always" with it warns once). - Server rendering. The server and the first client render are the popup.
native="auto"reads(pointer: coarse)once, right after mount, and never listens for a change: a rendering that swapped under the user would drop their focus to the page, so the rendering never changes after that first update (listbox-custom.test.tsx › native="auto" reads the pointer once after mount: a later change never swaps the rendering,listbox-custom.test.tsx › the server markup has the combobox, a closed popup and a hidden input, and no options). - No placeholder as the only label. The Field's label is always visible; the placeholder is part of the name only as a hint (4.1.2 Name, Role, Value (A), 3.3.2 Labels or Instructions (A)).
- Every part merges the consumer's class, handlers and refs with its own. For another element, spread the
useListboxprop objects on your own.Listbox.Optionkeeps its role. - Development warnings: native rendering inside a
Toolbar.Root(the trigger and itsToolbar.Itemare gone, so setnative="never"), a part outside a Root, a trigger without a name, an option whose item is not in the list,native="always"withmultiple,virtualizewithgroups, andvirtualizewith aListbox.Listwhose children aren't a function.
It announces nothing.
What you need to do#
- A
Field.Labelwith a visible question, always. A placeholder is not a label. Outside a Field, give the triggeraria-labeloraria-labelledby, and theListbox.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. Don't render the item's own text twice:Listbox.OptionshowsitemToString(item)unless you give it children. - A rich option (an icon, a description) must still have a plain text name, and it shows only in the popup: the native rendering shows the text only. Choose
native="never"when the rich content matters on touch devices too, andnative="always"where one frame of the custom trigger on a phone is a problem. - Keep the list in a meaningful order, short enough to scan, and for more than about 15 options that a user would filter, use a Combobox. For several choices from a short list, prefer a CheckboxGroup.
- Give
itemToLangwhen item texts are in other languages than the page, such as a list of languages ("Suomi" for Finnish, "Nynorsk" for Norwegian Nynorsk): each text is then read in its own language (3.1.2 Language of Parts (AA)). Returnundefinedfor the page's language. Combobox and Autocomplete do not haveitemToLang: their value is one<input>text. - Put the choice that means "no answer" in the list as a real option, if "no answer" is valid.
- Validate and set
invalidyourself, with a Field.ErrorMessage that says what to do ("Choose a municipality"). Don't change the page, submit or move focus when the value changes (3.2.2 On Input (A)). - Pass
valueandonValueChange, ordefaultValueandnamefor a plain<form>. - For thousands of options, filter or split the list first, and use
virtualizeonly for what stays long. GiveListbox.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 every Listbox a visible label, in a Field. A placeholder is not a label: it disappears once something is chosen, and without a name a screen reader says only “combobox” (3.3.2 Labels or Instructions, 4.1.2 Name, Role, Value).
Visual and modes#
- Focus indicator: the standard focus ring, at least 2px thick with at least 3:1 contrast, around the trigger and around the native select. The active option is shown by a bar at its start and a tinted fill, never by colour alone, and the chosen option by a tick (1.4.1 Use of Color (A), 2.4.7 Focus Visible (AA)).
- Target size: the trigger and each option are never smaller than 24 by 24 CSS pixels, and larger in the default density. The trigger is full width, or the width of a class you add (2.5.8 Target Size (Minimum) (AA)).
- Colour: the trigger looks like a text input: a visible edge, a thicker edge when invalid and a dashed edge when disabled, so state is never shown by colour alone. The popup has its own surface, edge and shadow. The chevron takes the text colour and is not the only sign that this is a select.
- forced-colors behaviour: system colours. The trigger keeps a visible edge, a thicker one when invalid and a dashed one when disabled. The popup keeps a visible edge. The active option uses the system's highlight colours and keeps its bar, and the chosen option keeps its tick. The native select returns to the native appearance.
- reduced-motion behaviour: nothing moves. The trigger's edge and fill change with a short transition only when the user has not asked for reduced motion; the popup does not animate its position or opacity.
- Reflow: the trigger is as wide as its column and no wider, and the popup is at least as wide as the trigger and never wider than the viewport; long option text wraps in the popup, and the chosen text wraps in the closed trigger, which grows with it (never an ellipsis).
- RTL: the chevron is at the left, the text starts at the right, and the tick is at the left of the option.
Focus management#
- Initial focus: not moved. Opening never moves DOM focus (a keyboard user stays on the trigger), and no option is active until an arrow key, Home, End, Page Up, Page Down or a typed letter, 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 trigger: it chooses the active option (one choice) or just closes the popup, and moves on (2.1.2 No Keyboard Trap (A)). - Restore to: the trigger, which never lost focus. Escape and a press on an option keep it there. 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 trigger and flips above it when there is no room, so it never covers the trigger (2.4.11 Focus Not Obscured (Minimum) (AA)). 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, and applies to the stylable popup only: the native <select> ignores it. The rules below are enforced in one place in the core package, and the same tests cover Listbox, Combobox and Autocomplete.
- Keep what matters mounted. The active option and every chosen option are always rendered, even when they are scrolled out of view.
aria-activedescendantcan only point at an element that is in the page, so it never points at nothing (4.1.2 Name, Role, Value (A);listbox-virtual.test.tsx › ArrowDown and ArrowUp always leave aria-activedescendant on an option in the page). - Scroll before you point. A key that moves the active option calls
scrollToIndexfor it, and the option is rendered in the same commit that setsaria-activedescendant, so the element exists and is in view when assistive technology looks (2.4.3 Focus Order (A), 2.4.7 Focus Visible (AA);listbox-virtual.test.tsx › Home and End reach the first and the last option, rendered and in view). A pointer move doesn't scroll: the option is already under the pointer. On opening, the chosen option is scrolled to. - Navigate the data, not the DOM. Home, End, Page Up, Page Down, the arrows and typeahead work on the whole list, not on the options that happen to be rendered (2.1.1 Keyboard (A);
listbox-virtual.test.tsx › typing a letter reaches an option that was not rendered, and å, ä and ö stay apart). - Expose the full size. Every rendered option has
aria-setsize(the number of options) andaria-posinset(its place, from 1), so a screen reader says "3 of 10 000" and not "3 of 14" (1.3.1 Info and Relationships (A);listbox-virtual.test.tsx › every rendered option carries aria-setsize and its place in the whole list). - The list is the scroll element. The
role="listbox"element scrolls and carriesdata-virtualized. Inside it, one sizer element (kv-listbox-virtual-sizer) has the height of the whole list, and each rendered option is absolutely positioned in it withdata-index. The geometry is inline (position, block size andtranslateY) and nothing else: no colour, spacing or type, so a virtualized list lays out without a theme. The list 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: a partly renderedrole="group"gives a screen reader the wrong group. 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. Filter first (a Combobox), paginate, or virtualize a list that stays long. A virtualized list is for a popup the user operates with the keys listed above.
- Screen-reader support varies.
aria-setsizeandaria-posinseton options, andaria-activedescendantinto a virtualized list, are read differently by NVDA, JAWS, VoiceOver and TalkBack. Test a long list with your own assistive technology.
Rich options#
An option holds any markup. The four parts are optional, and Combobox and Autocomplete share them.
- Name. With a
Listbox.OptionTextthe option hasaria-labelledbypointing at it, so the name is that text alone. Without one the name is the option's whole text content. Anaria-labeloraria-labelledbyof the consumer's wins (4.1.2 Name, Role, Value (A), 2.5.3 Label in Name (A)). - Description. With a
Listbox.OptionDescriptionthe option hasaria-describedbypointing at it, after anyaria-describedbyof the consumer's. - Decorative parts.
Listbox.OptionIconandListbox.OptionIndicatorarearia-hidden="true". An image inside carriesalt=""(1.1.1 Non-text Content (A)).aria-selectedis unchanged: the indicator is decoration, and its children show only on the chosen option. itemToStringequals the OptionText. Typeahead, filtering and the trigger's value useitemToString. A development warning fires when the OptionText's text differs, and a part outside an option warns once.- Native rendering takes plain text: the parts don't render, each
<option>isitemToString. - Risk. Support for a description on the active option, read through
aria-activedescendant, varies across NVDA, JAWS, VoiceOver and TalkBack. The name is always right; the fallback is that the description is not announced. Never put essential information only in the description. - Reflow. Two-line options wrap at 320px (1.4.10 Reflow (AA)).
- Each rule above has a test.
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, the value,
aria-selected,aria-disabled,aria-multiselectable, groups and the native select. - 1.4.1 Use of Color (A), 1.4.11 Non-text Contrast (AA): the edge, the invalid width, the active bar and the tick.
- 1.4.10 Reflow (AA): 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) and 3.2.2 On Input (A): the APG keys, one Tab stop, no context change when choosing.
- 2.4.7 Focus Visible (AA), 2.4.11 Focus Not Obscured (Minimum) (AA). The default theme's ring also meets 2.4.13 Focus Appearance (AAA), which is not counted toward the AA bar.
- 2.5.3 Label in Name (A), 2.5.8 Target Size (Minimum) (AA).
- 3.1.2 Language of Parts (AA):
itemToLangputslangon the options and the value (listbox-custom.test.tsx › itemToLang (3.1.2)). - 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. 1.3.5 Identify Input Purpose (AA):
autoCompletefor country, language and similar applies to the native select only.
Keyboard#
- Focus
- aria-activedescendant for the popup, DOM focus stays on the trigger. Native for the native rendering, which is the browser's own.
- Selection follows focus
- no (Enter, Space, Tab or a click chooses an option, and the arrow keys only move the highlight)
- Arrows wrap
- no
- Shortcuts
- none
The trigger and the native select are one Tab stop. Home and End, and a letter, also open the closed popup, as in the APG example. The arrows are vertical, so they don't flip in right-to-left text. The rows marked "popup" are the stylable rendering. The native rows describe Chromium on Windows and Linux, which the component tests drive: on macOS and in Safari the arrow keys, Space and Enter open the list instead of changing the value. The native rendering intercepts nothing. In the popup, 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 trigger (popup) | Moves focus to the trigger. One stop Test: listbox-custom.test.tsx › Tab leaves the listbox: it is one tab stop |
| Shift+Tab | on the trigger, popup closed | Moves focus to the previous focusable element Test: listbox-custom.test.tsx › Shift+Tab on the closed trigger moves focus to the previous element |
| Tab | disabled trigger | Skips it Test: listbox-custom.test.tsx › a disabled listbox does not open, and is not focusable |
| ArrowDown | on the closed trigger (popup) | Opens the popup and activates the chosen option, or the first. Focus stays on the trigger Test: listbox-custom.test.tsx › ArrowDown on the closed trigger opens it and activates the first option |
| ArrowUp | on the closed trigger (popup) | Opens the popup and activates the chosen option, or the last Test: listbox-custom.test.tsx › ArrowUp on the closed trigger opens it and activates the last option |
| Enter / Space | on the closed trigger (popup) | Opens the popup and activates the chosen option, or the first Test: listbox-custom.test.tsx › Enter and Space on the closed trigger open it |
| Alt+ArrowDown | on the trigger (popup) | Opens the popup without activating an option Test: listbox-custom.test.tsx › Alt+ArrowDown opens the popup without activating an option |
| ArrowDown | popup open | Activates the next option, and scrolls it into view. Stops at the last option Test: listbox-custom.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: listbox-custom.test.tsx › ArrowDown and ArrowUp move the active option and stop at the ends: no wrap |
| Home / End | on the trigger (popup) | Opens the popup if it is closed, and activates the first or the last option Test: listbox-custom.test.tsx › Home and End activate the first and the last option |
| PageDown / PageUp | popup open | Moves the active option ten on or back, and stops at the last or the first Test: listbox-custom.test.tsx › PageDown and PageUp move ten options, and stop at the ends |
| Enter | popup open, an option is active | Chooses the active option and closes the popup. Focus stays on the trigger. Several choices: toggles it and the popup stays open Test: listbox-custom.test.tsx › Enter chooses the active option, closes the popup and keeps focus on the trigger |
| Enter | popup open, no option is active | Nothing: no option is chosen, and the popup stays open Test: listbox-custom.test.tsx › Enter with no active option chooses nothing and leaves the popup open |
| Space | popup open, an option is active | Chooses the active option (several choices: toggles it). During a typeahead word it is a space in the word Test: listbox-custom.test.tsx › Space chooses the active option |
| Tab | popup open, one choice, an option is active | Chooses the active option, closes the popup and moves focus to the next focusable element Test: listbox-custom.test.tsx › Tab chooses the active option and moves focus on |
| Shift+Tab | popup open, one choice, an option is active | Chooses the active option, closes the popup and moves focus to the previous focusable element Test: listbox-custom.test.tsx › Shift+Tab chooses the active option and moves focus back |
| Tab / Shift+Tab | popup open, several choices or no option active | Closes the popup without choosing, and moves focus on Test: listbox-custom.test.tsx › Tab closes the popup without choosing the active option |
| Escape | popup open | Closes the popup. The value stays, and focus stays on the trigger Test: listbox-custom.test.tsx › Escape closes the popup and keeps the value and the focus |
| Escape | popup closed | Nothing: the key is the page's own Test: listbox-custom.test.tsx › Escape does nothing while the popup is closed |
| Alt+ArrowUp | popup open | Chooses the active option and closes the popup Test: listbox-custom.test.tsx › Alt+ArrowUp chooses the active option and closes the popup |
| any character | on the trigger (popup) | Typeahead: opens the popup and activates the next option whose text starts with what you typed. The word ends after a pause. The same letter again cycles Test: listbox-custom.test.tsx › typing a letter opens the popup and activates the next option that starts with it |
| any character | on the trigger, Swedish (popup) | Typeahead keeps å, ä and ö apart from a and o Test: listbox-custom.test.tsx › typeahead keeps å, ä and ö apart from a and o in Swedish |
| ArrowDown / ArrowUp | popup open, a disabled option | The disabled option can be reached and is read as unavailable. Enter, Space and a click don't choose it Test: listbox-custom.test.tsx › a disabled option can be reached with the arrow keys and cannot be chosen |
| Enter | popup open, several choices | Toggles the active option. The popup stays open, so more can be chosen Test: listbox-custom.test.tsx › Enter and Space toggle the active option, and the popup stays open |
| Pointer press | on the trigger (popup) | Opens the popup, or closes it when it is open Test: listbox-custom.test.tsx › a press on the trigger opens the popup, and a second press closes it |
| Pointer press | on an option | Chooses it, and keeps focus on the trigger. A disabled option does nothing Test: listbox-custom.test.tsx › a click on an option chooses it, closes the popup and keeps focus on the trigger |
| Pointer move | over an option | Makes it the active option Test: listbox-custom.test.tsx › moving the pointer over an option makes it the active option |
| Pointer press | outside the popup and the trigger | Closes the popup. A control that is pressed keeps the focus Test: listbox-custom.test.tsx › a press outside closes the popup, and focus stays where the press put it |
| ArrowDown / ArrowUp | popup open, right to left | Still the next and the previous option: vertical arrows don't flip in right-to-left text Test: listbox-custom.test.tsx › right to left: ArrowDown and ArrowUp still mean the next and the previous option |
| Home / End | popup, virtualized | Activates the first or 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: listbox-virtual.test.tsx › Home and End reach the first and 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: listbox-virtual.test.tsx › 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: listbox-virtual.test.tsx › PageDown and PageUp move ten options that may not be rendered |
| any character | on the trigger, virtualized | Typeahead reaches an option that wasn't rendered: it is rendered and scrolled into view first, and å, ä and ö stay apart from a and o Test: listbox-virtual.test.tsx › typing a letter reaches an option that was not rendered, and å, ä and ö stay apart |
| ArrowDown | on the closed trigger, virtualized, one chosen | Opens the popup scrolled to the chosen option, which is rendered and active, however far down the list it is Test: listbox-virtual.test.tsx › opening with a key activates the chosen option, far from the top |
| Tab | before the select (native) | Moves focus to the select Test: listbox.test.tsx › sets data-focus-visible on keyboard focus only, and Tab moves on |
| Shift+Tab | on the select (native) | Moves focus to the previous focusable element Test: listbox.test.tsx › Shift+Tab leaves the select backwards |
| Tab | disabled select (native) | Skips it (native disabled)Test: listbox.test.tsx › Tab skips a disabled select |
| ArrowDown | on the closed select (native) | Chooses the next option and reports onValueChange (no wrap). Where the platform opens the list instead, it opensTest: listbox.test.tsx › ArrowDown chooses the next option and ArrowUp the previous one, without wrapping |
| ArrowUp | on the closed select (native) | Chooses the previous option (no wrap) Test: listbox.test.tsx › ArrowDown chooses the next option and ArrowUp the previous one, without wrapping |
| Home / End | on the closed select (native) | Chooses the first and the last option Test: listbox.test.tsx › Home and End choose the first and the last option |
| any character | on the closed select (native) | Typeahead: chooses the next option that starts with the typed text Test: listbox.test.tsx › typing a letter chooses the option that starts with it |
| Alt+ArrowDown | on the closed select (native) | Opens the list without changing the value Test: listbox.test.tsx › Alt+ArrowDown opens the list without changing the value, and Escape closes it |
| Escape | on the open list (native) | Closes the list and keeps the value Test: listbox.test.tsx › Alt+ArrowDown opens the list without changing the value, and Escape closes it |
Space and Enter open the native list on most platforms, and Enter in the open list chooses the highlighted option and closes it (native). Clicking the label focuses the select (listbox.test.tsx › clicking the label focuses the select) or, for the popup, the trigger (listbox-custom.test.tsx › clicking the label focuses the trigger).
API reference#
import { Listbox, useListbox } from '@kvirn-ui/react'Listbox.Root
Renders no element of its own. It renders hidden inputs after its children when you give name, and with native="always" (or "auto" on a touch device) it renders a native <select> instead of its children. Put a Listbox.Trigger and a Listbox.Popup inside it, in a Field.
| 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 trigger, read by typeahead, and the label of the native option. |
itemToLang | (item: TItem) => string | undefined | – | The language of an item’s text, as a BCP 47 code such as fi, or undefined for the page’s language. Sets lang on each native option, each popup option and each chosen text in the trigger’s value (WCAG 3.1.2). Combobox and Autocomplete do not have it. |
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. |
multiple | boolean | false | Several choices. The popup stays open after a choice and each option toggles. Always the popup, never the native select. |
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' | 'native' }) => void | – | Called with the chosen key (an array with multiple) when the user chooses. It only reports: update value yourself when it is controlled. |
native | 'auto' | 'always' | 'never' | 'auto' | When the browser’s own <select> renders instead of the popup. auto: on a touch device, for one choice. always and never force it. multiple is always the popup. |
name | string | – | A hidden input per chosen key for a plain form (the native select carries the name itself). |
placeholder | string | – | Shown while nothing is chosen, and the label of the native select’s empty option. Never the only label. |
autoComplete | string | – | The autocomplete attribute of the native select, such as address-level2 (WCAG 1.3.5). |
disabled | boolean | false | Disables it. A disabled Field disables it too. |
id | string | – | The trigger’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 trigger-press, option-press, key, escape, outside-press, blur or light-dismiss. 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 trigger and the popup, in pixels. |
padding | number | 8 | The space kept to the edge of the viewport, in pixels. |
messages | Partial<KvirnMessages['combobox']> | – | Per-instance text. noResults is the default text of Listbox.Empty. |
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. The native select ignores it. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-native | always | The class of the native <select> that native renders. |
Listbox.Trigger
Renders <div role="combobox" tabindex="0">, as in the select-only combobox pattern of the ARIA Authoring Practices Guide (APG). Focus stays on it. It is named by the Field’s label followed by the value, and renders a Listbox.Value when it has no children. It takes every attribute of a <div> and passes ref to it. Theming is on Theming.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-trigger | always | The part class. The default theme styles it. |
role | "combobox" | A select-only combobox. Focus stays on it. |
tabindex | "0", or yours | One Tab stop. A disabled trigger has none of its own. |
aria-expanded | "true" or "false" | Whether the popup is open. |
aria-controls | the list’s id | Points at the list, which stays in the page while the popup is closed. |
aria-haspopup | "listbox" | The trigger opens a list of options. |
aria-activedescendant | an option’s id | The active option, only while open and only when it is rendered. |
aria-labelledby | the Field’s label, then the value | Its name. Outside a Field, give it aria-label or aria-labelledby. |
aria-describedby, aria-invalid, aria-required, aria-disabled | from the Field | The help text and error describe it. The Field sets the state. |
data-open | present or absent | The popup is open. |
data-focus-visible | present or absent | The trigger 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 Listbox is disabled. |
Listbox.Value
Renders <span> with the chosen text, or the placeholder. It is part of the trigger’s name.
| Prop | Type | Default | Description |
|---|---|---|---|
placeholder | string | The Root’s placeholder | Shown while nothing is chosen. Never the only label. |
children | ReactNode | (selectedItems: readonly TItem[]) => ReactNode | The chosen texts, joined with a comma | What shows when something is chosen. A function gets the chosen items. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-value | always | The part class. |
lang | a language code, or absent | On a span around each chosen text, when you give itemToLang and Value has no children of its own. |
data-placeholder | present or absent | Nothing is chosen, so the placeholder shows. |
Listbox.Popup
Renders <div popover="manual"> with no role, in the top layer, always rendered and hidden by the browser while closed. It is as wide as the trigger and flips when there is no room. Focus never enters it. Combobox and Autocomplete use the same part.
| 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. |
Listbox.List
Renders <div role="listbox"> inside the popup: the element aria-controls points at, named by the Field’s label, and the part that scrolls. It is always in the page, and hidden while the popup is open with no option.
| 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. |
Listbox.Option
Renders <div role="option"> with aria-selected, and aria-disabled when the item is disabled. A click chooses it.
| 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. |
Listbox.OptionIcon
Renders <span aria-hidden="true"> at the start of an option, for an icon, a flag or an avatar. It is decorative, so anything it means must also be in the text. The native select does not render it.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-option-icon | always | The part class. |
Listbox.OptionText
Renders <span> that the option’s aria-labelledby points at, so its text is the option’s name and a description is not. Keep it equal to itemToString: a development warning fires when it is not.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-option-text | always | The part class. |
Listbox.OptionDescription
Renders <span> that the option’s aria-describedby points at. Screen readers differ in whether they read it for the active option, so never put the only copy of something essential here.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-option-description | always | The part class. |
Listbox.OptionIndicator
Renders <span aria-hidden="true"> at the end of an option, with data-selected while it is chosen. With no children the default theme draws a check in it. Children replace the check and show only on the chosen option.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-option-indicator | always | The part class. |
data-selected | present or absent | The option is chosen. |
Listbox.Group
Renders <div role="group"> named by its Listbox.GroupLabel. Listbox.List renders one per group when the Root has groups.
| 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. |
Listbox.GroupLabel
Renders <div> with the group’s visible name. The group’s aria-labelledby points at it.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-group-label | always | The part class. |
Listbox.Empty
Renders <div> with plain text, shown only while the popup is open and there is no option. It is not an option and not in the listbox. Its default text is the locale’s “No results”.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-listbox-empty | always | The part class. |
useListbox
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 trigger, read by typeahead, and the label of the native option. |
itemToLang | (item: TItem) => string | undefined | – | The language of an item’s text, as a BCP 47 code such as fi, or undefined for the page’s language. Sets lang on each native option, each popup option and each chosen text in the trigger’s value (WCAG 3.1.2). Combobox and Autocomplete do not have it. |
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. |
multiple | boolean | false | Several choices. The popup stays open after a choice and each option toggles. Always the popup, never the native select. |
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' | 'native' }) => void | – | Called with the chosen key (an array with multiple) when the user chooses. It only reports: update value yourself when it is controlled. |
native | 'auto' | 'always' | 'never' | 'auto' | When the browser’s own <select> renders instead of the popup. auto: on a touch device, for one choice. always and never force it. multiple is always the popup. |
name | string | – | A hidden input per chosen key for a plain form (the native select carries the name itself). |
placeholder | string | – | Shown while nothing is chosen, and the label of the native select’s empty option. Never the only label. |
autoComplete | string | – | The autocomplete attribute of the native select, such as address-level2 (WCAG 1.3.5). |
disabled | boolean | false | Disables it. A disabled Field disables it too. |
id | string | – | The trigger’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 trigger-press, option-press, key, escape, outside-press, blur or light-dismiss. 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 trigger and the popup, in pixels. |
padding | number | 8 | The space kept to the edge of the viewport, in pixels. |
messages | Partial<KvirnMessages['combobox']> | – | Per-instance text. noResults is the default text of Listbox.Empty. |
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. The native select ignores it. |
Result
| Prop | Type | Default | Description |
|---|---|---|---|
isNative | boolean | – | The native <select> renders instead of the popup. Listbox.Root checks this. |
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 trigger has keyboard (:focus-visible) focus. |
entries | readonly ListboxEntry<TItem>[] | – | Every option, 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. |
activeKey | string | undefined | – | The active option’s key. Undefined while closed and until the user moves. |
selectedKeys | readonly string[] | – | The chosen keys. |
selectedItems | readonly TItem[] | – | The chosen items, in the order chosen. |
selectedLabels | readonly string[] | – | The chosen items’ texts, in the same order. |
placeholder | string | undefined | – | The placeholder from the options. |
emptyText | string | – | The text of Listbox.Empty unless you give it children: combobox.noResults. |
triggerProps | ListboxTriggerPartProps | – | Spread on a <div>: role combobox, tabIndex, ARIA, handlers and a ref. |
valueProps | ListboxValuePartProps | – | Spread on the element that shows the chosen text. |
popupProps | ListboxPopupPartProps | – | Spread on the popup: popover="manual", its id and ref. |
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. Empty with the native rendering. | |
nativeValue | string | – | For the native rendering: the chosen key, or an empty string. |
selectFromNative | (value: string) => void | – | For the native rendering: the user chose value (an empty string is the empty option). |
Strings
These are the default texts in @kvirn-ui/i18n.
For your whole app, pass messages to KvirnProvider. For one Listbox, pass its messages prop.
combobox.noResults
The default text of Listbox.Empty, shown while the popup is open and there is no option.
| Language | Default text |
|---|---|
| Svenska | Inga resultat |
| Suomi | Ei tuloksia |
| Norsk bokmål | Ingen treff |
| Norsk nynorsk | Ingen treff |
| English | No results |
Known issues#
aria-activedescendanton VoiceOver and TalkBack has known gaps. That is why a single choice is the native<select>on touch devices undernative="auto". Testnative="never"andmultipleon iOS and Android with your own assistive technology.- The native list is the browser's. Its colours, size and font follow the OS and can't be styled to the theme. In
forced-colorsand in the high-contrast themes it follows the user's colours. - The chevron of the native select is drawn in CSS. A
<select>takes no pseudo-element, and a wrapper would change the markup. In forced colours the theme returns to the native appearance, which draws its own arrow. The popup's trigger draws its chevron with a pseudo-element. - The first frame on a touch device. With
native="auto"the server and the first client render are the popup trigger, and a coarse pointer switches to the native select right after mount, before the user can interact. The pointer is not watched afterwards (a laptop that gains a touch screen keeps its rendering until the page loads again). Usenative="always"to avoid the first frame. - Virtualization is opt-in and has limits. Without
virtualize, every 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. The accessibility checker axe treats the combobox popup as exempt from its scrollable-region rule.
- Keys differ by platform for the native rendering. The Keyboard rows describe Chromium on Windows and Linux (tested); macOS and Safari open the list for the arrow keys.
- Keyboard tests run in Chromium only. The keyboard rows run in Vitest browser mode on Chromium, not in WebKit. Test in Safari with your own assistive technology. Check
popover="manual", the outside press and Escape in Safari 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 | listbox.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | listbox.test.tsx › the Field’s label is the name, and the description and error describe it; expectNoA11yViolations |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 43 rows, each names a test (listbox-custom.test.tsx › Tab leaves the listbox: it is one tab stop) |
| Focus order and management | pass | n/a | pass | listbox-custom.test.tsx asserts focus (toHaveFocus); first rule: Tab leaves the listbox: it is one tab stop |
| 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 | |
| Component-specific | ||||
itemToLang: does the trigger read the chosen option in its own language (for example Finnish)? The language of a span inside a button's computed name is often lost | pending | pending | pending |
What to check#
With a screen reader and the keyboard, try:
- Tab to the listbox: the label, the chosen value or the placeholder, "combobox" and "collapsed" are read.
- Down Arrow opens it. Focus stays on the trigger, and the active option is read with its place in the list.
- Up Arrow, Down Arrow, Home and End move. A disabled option is read as unavailable.
- Enter chooses. Escape on another try leaves the value unchanged, and the value is read back.
- With
multiple, Enter toggles and the popup stays open. Each state is read. - On iOS or Android with
native="auto"the phone's own picker opens. - With
itemToLang, a Finnish option is read in Finnish.