ComboBox allow users to choose a single option from a collapsible list of options when space is limited.
Content
ComboBox follows the Collection Components API, accepting both static and dynamic collections. This example shows a dynamic collection, passing a list of objects to the items prop, and a function to render the children.
import {ComboBox, ComboBoxItem} from '@react-spectrum/s2/ComboBox';
import Binoculars from '@react-spectrum/s2/icons/Binoculars';
function Example() {
let options = [
{ id: 1, name: 'Aardvark' },
{ id: 2, name: 'Cat' },
{ id: 3, name: 'Dog' },
{ id: 4, name: 'Kangaroo' },
{ id: 5, name: 'Koala' },
{ id: 6, name: 'Penguin' },
{ id: 7, name: 'Snake' },
{ id: 8, name: 'Turtle' },
{ id: 9, name: 'Wombat' }
];
return (
<ComboBox label="Animals" defaultItems={options} placeholder="Select an animal" prefix={<Binoculars />}>
{(item) => <ComboBoxItem>{item.name}</ComboBoxItem>}
</ComboBox>
);
}
Slots
ComboBoxItem supports icons, avatars, and label and description text slots.
import {Avatar} from '@react-spectrum/s2/Avatar';
import {ComboBox, ComboBoxItem, Text} from '@react-spectrum/s2/ComboBox';
import {style} from '@react-spectrum/s2/style' with {type: 'macro'};
import Comment from '@react-spectrum/s2/icons/Comment';
import Edit from '@react-spectrum/s2/icons/Edit';
import UserSettings from '@react-spectrum/s2/icons/UserSettings';
const users = Array.from({length: 5}, (_, i) => ({
id: `user${i + 1}`,
name: `User ${i + 1}`,
email: `user${i + 1}@example.com`,
avatar: 'https://i.imgur.com/kJOwAdv.png'
}));
<div className={style({display: 'flex', gap: 12, flexWrap: 'wrap'})}>
<ComboBox label="Permissions" defaultSelectedKey="read" placeholder="Select a permission level">
<ComboBoxItem id="read" textValue="Read">
<Comment />
<Text slot="label">Read</Text>
<Text slot="description">Comment only</Text>
</ComboBoxItem>
<ComboBoxItem id="write" textValue="Write">
<Edit />
<Text slot="label">Write</Text>
<Text slot="description">Read and write only</Text>
</ComboBoxItem>
<ComboBoxItem id="admin" textValue="Admin">
<UserSettings />
<Text slot="label">Admin</Text>
<Text slot="description">Full access</Text>
</ComboBoxItem>
</ComboBox>
<ComboBox label="Share" defaultItems={users} defaultSelectedKey="user1" placeholder="Select a user">
{(item) => (
<ComboBoxItem id={item.id} textValue={item.name}>
<Avatar slot="avatar" src={item.avatar} />
<Text slot="label">{item.name}</Text>
<Text slot="description">{item.email}</Text>
</ComboBoxItem>
)}
</ComboBox>
</div>
Accessibility
Sections
Use the <ComboBoxSection> component to group options. A <Header> element, with a <Heading> and optional description slot can be included to label a section. Sections without a header must have an aria-label.
import {ComboBox, ComboBoxItem, ComboBoxSection, Header, Heading, Text} from '@react-spectrum/s2/ComboBox';
<ComboBox label="Preferred fruit or vegetable" placeholder="Select an option">
<ComboBoxSection>
<Header>
<Heading>Fruit</Heading>
<Text slot="description">Sweet and nutritious</Text>
</Header>
<ComboBoxItem id="apple">Apple</ComboBoxItem>
<ComboBoxItem id="banana">Banana</ComboBoxItem>
<ComboBoxItem id="orange">Orange</ComboBoxItem>
<ComboBoxItem id="grapes">Grapes</ComboBoxItem>
</ComboBoxSection>
<ComboBoxSection>
<Header>
<Heading>Vegetable</Heading>
<Text slot="description">Healthy and savory</Text>
</Header>
<ComboBoxItem id="broccoli">Broccoli</ComboBoxItem>
<ComboBoxItem id="carrots">Carrots</ComboBoxItem>
<ComboBoxItem id="spinach">Spinach</ComboBoxItem>
<ComboBoxItem id="lettuce">Lettuce</ComboBoxItem>
</ComboBoxSection>
</ComboBox>
Asynchronous loading
Use the loadingState and onLoadMore props to enable async loading and infinite scrolling.
import {ComboBox, ComboBoxItem} from '@react-spectrum/s2/ComboBox';
import {useAsyncList} from '@react-spectrum/s2/useAsyncList';
interface Character {
name: string
}
function Example() {
let list = useAsyncList<Character>({
async load({signal, cursor, filterText}) {
if (cursor) {
cursor = cursor.replace(/^http:\/\//i, 'https://');
}
let res = await fetch(cursor || `https://swapi.py4e.com/api/people/?search=${filterText}`, {signal});
let json = await res.json();
return {
items: json.results,
cursor: json.next
};
}
});
return (
<ComboBox
label="Star Wars Character Lookup"
placeholder="Select a character"
items={list.items}
inputValue={list.filterText}
onInputChange={list.setFilterText}
loadingState={list.loadingState}
onLoadMore={list.loadMore}>
{item => <ComboBoxItem id={item.name} textValue={item.name}>{item.name}</ComboBoxItem>}
</ComboBox>
);
}
Actions
Use the onAction prop on a <ComboBoxItem> to perform a custom action when the item is pressed. This example adds a "Create" action for the current input value.
import {ComboBox, ComboBoxItem} from '@react-spectrum/s2/ComboBox';
import {useState} from 'react';
function Example() {
let [inputValue, setInputValue] = useState('');
return (
<ComboBox
label="Favorite Animal"
placeholder="Select an animal"
inputValue={inputValue}
onInputChange={setInputValue}>
{inputValue.length > 0 && (
<ComboBoxItem onAction={() => alert('Creating ' + inputValue)}>
{`Create "${inputValue}"`}
</ComboBoxItem>
)}
<ComboBoxItem>Aardvark</ComboBoxItem>
<ComboBoxItem>Cat</ComboBoxItem>
<ComboBoxItem>Dog</ComboBoxItem>
<ComboBoxItem>Kangaroo</ComboBoxItem>
<ComboBoxItem>Panda</ComboBoxItem>
<ComboBoxItem>Snake</ComboBoxItem>
</ComboBox>
);
}
Links
Use the href prop on a <ComboBoxItem> to create a link. See the getting started guide to learn how to integrate with your framework. Link items in a ComboBox are not selectable.
import {ComboBox, ComboBoxItem} from '@react-spectrum/s2/ComboBox';
<ComboBox label="Bookmarks" placeholder="Select a bookmark">
<ComboBoxItem href="https://adobe.com/" target="_blank">Adobe</ComboBoxItem>
<ComboBoxItem href="https://apple.com/" target="_blank">Apple</ComboBoxItem>
<ComboBoxItem href="https://google.com/" target="_blank">Google</ComboBoxItem>
<ComboBoxItem href="https://microsoft.com/" target="_blank">Microsoft</ComboBoxItem>
</ComboBox>
Selection
Use the defaultSelectedKey or selectedKey prop to set the selected item. The selected key corresponds to the id prop of an item. Items can be disabled with the isDisabled prop. See the selection guide for more details.
Current selection: bison
import {ComboBox, ComboBoxItem, type Key} from '@react-spectrum/s2/ComboBox';
import {useState} from 'react';
function Example() {
let [animal, setAnimal] = useState<Key | null>("bison");
return (
<div>
<ComboBox
label="Pick an animal"
placeholder="Select an animal"
selectedKey={animal}
onSelectionChange={setAnimal}>
<ComboBoxItem id="koala">Koala</ComboBoxItem>
<ComboBoxItem id="kangaroo">Kangaroo</ComboBoxItem>
<ComboBoxItem id="platypus" isDisabled>Platypus</ComboBoxItem>
<ComboBoxItem id="eagle">Bald Eagle</ComboBoxItem>
<ComboBoxItem id="bison">Bison</ComboBoxItem>
<ComboBoxItem id="skunk">Skunk</ComboBoxItem>
</ComboBox>
<p>Current selection: {animal}</p>
</div>
);
}
Input value
Use the inputValue or defaultInputValue prop to set the value of the input field. By default, the value will be reverted to the selected item on blur. Set the allowsCustomValue prop to enable entering values that are not in the list.
Current input value: Kangaroo
Fully controlled
Both inputValue and selectedKey can be controlled simultaneously. However, each interaction will only trigger either onInputChange or onSelectionChange, not both. When controlling both props, you must update both values accordingly.
Current selected major id: Current input text:
import {ComboBox, ComboBoxItem, type Key} from '@react-spectrum/s2/ComboBox';
import {style} from '@react-spectrum/s2/style' with {type: 'macro'};
import {useState} from 'react';
function ControlledComboBox() {
let [fieldState, setFieldState] = useState<{selectedKey: Key | null, inputValue: string}>({
selectedKey: null,
inputValue: ''
});
let onSelectionChange = (id: Key | null) => {
// Update inputValue when selectedKey changes.
setFieldState({
inputValue: id ? (options.find(o => o.id === id)?.name ?? '') : '',
selectedKey: id
});
};
let onInputChange = (value: string) => {
// Reset selectedKey to null if the input is cleared.
setFieldState(prevState => ({
inputValue: value,
selectedKey: value === '' ? null : prevState.selectedKey
}));
};
return (
<div>
<ComboBox
label="Pick a engineering major"
placeholder="Select a major"
defaultItems={options}
selectedKey={fieldState.selectedKey}
inputValue={fieldState.inputValue}
onSelectionChange={onSelectionChange}
onInputChange={onInputChange}>
{item => <ComboBoxItem>{item.name}</ComboBoxItem>}
</ComboBox>
<pre className={style({font: 'body'})}>
Current selected major id: {fieldState.selectedKey}{'\n'}
Current input text: {fieldState.inputValue}
</pre>
</div>
);
}
Forms
Use the name prop to submit the id of the selected item to the server. Set the isRequired prop to validate that the user selects a value, or implement custom client or server-side validation. See the Forms guide to learn more.
Popover options
Use the menuTrigger prop to control when the popover opens:
input(default): popover opens when the user edits the input text.focus: popover opens when the user focuses the input.manual: popover only opens when the user presses the trigger button or uses the arrow keys.
The align, direction, shouldFlip and menuWidth props control the behavior of the popover.
API
<ComboBox>
<ComboBoxItem>
<Icon /> or <Avatar />
<Text slot="label" />
<Text slot="description" />
</ComboBoxItem>
<ComboBoxSection>
<Header>
<Heading />
<Text slot="description" />
</Header>
<ComboBoxItem />
</ComboBoxSection>
</ComboBox>
ComboBox
| Name | Type | Default |
|---|---|---|
allowsCustomValue | boolean | Default: — |
Whether the ComboBox allows a non-item matching input value to be set. | ||
menuTrigger | MenuTriggerAction | Default: 'input'
|
The interaction required to display the ComboBox menu. | ||
isDisabled | boolean | Default: — |
Whether the input is disabled. | ||
isReadOnly | boolean | Default: — |
Whether the input can be selected but not changed by the user. | ||
size | 'S'
| 'M'
| 'L'
| 'XL' | Default: 'M'
|
The size of the Combobox. | ||
prefix | ReactNode | Default: — |
The prefix to display in the ComboBox. A non-interactive element that appears before the input. | ||
styles | StylesProp | Default: — |
Spectrum-defined styles, returned by the | ||
placeholder | string | Default: — |
Temporary text that occupies the text input when it is empty. See MDN. | ||
children | ReactNode | | Default: — |
The contents of the collection. | ||
items | Iterable | Default: — |
The list of ComboBox items (controlled). | ||
defaultItems | Iterable | Default: — |
The list of ComboBox items (uncontrolled). | ||
loadingState | LoadingState | Default: — |
The current loading state of the ComboBox. Determines whether or not the progress circle should be shown. | ||
onLoadMore | | Default: — |
Handler that is called when more items should be loaded, e.g. while scrolling near the bottom. | ||
dependencies | ReadonlyArray | Default: — |
Values that should invalidate the item cache when using dynamic collections. | ||
selectedKey | Key | null | Default: — |
The currently selected key in the collection (controlled). | ||
defaultSelectedKey | Key | null | Default: — |
The initial selected key in the collection (uncontrolled). | ||
onSelectionChange | | Default: — |
Handler that is called when the selection changes. | ||
disabledKeys | Iterable | Default: — |
The item keys that are disabled. These items cannot be selected, focused, or otherwise interacted with. | ||
shouldFocusWrap | boolean | Default: — |
Whether keyboard navigation is circular. | ||
inputValue | string | Default: — |
The value of the ComboBox input (controlled). | ||
defaultInputValue | string | Default: — |
The default value of the ComboBox input (uncontrolled). | ||
onInputChange | | Default: — |
Handler that is called when the ComboBox input value changes. | ||
label | ReactNode | Default: — |
The content to display as the label. | ||
labelPosition | LabelPosition | Default: 'top'
|
The label's overall position relative to the element it is labeling. | ||
labelAlign | Alignment | Default: 'start'
|
The label's horizontal alignment relative to the element it is labeling. | ||
contextualHelp | ReactNode | Default: — |
A ContextualHelp element to place next to the label. | ||
isRequired | boolean | Default: — |
Whether user input is required on the input before form submission. | ||
isInvalid | boolean | Default: — |
Whether the input value is invalid. | ||
validate | | Default: — |
A function that returns an error message if a given value is invalid.
Validation errors are displayed to the user when the form is submitted
if | ||
validationBehavior | 'native' | 'aria' | Default: 'native'
|
Whether to use native HTML form validation to prevent form submission when the value is missing or invalid, or mark the field as required or invalid via ARIA. | ||
necessityIndicator | NecessityIndicator | Default: 'icon'
|
Whether the required state should be shown as an icon or text. | ||
description | ReactNode | Default: — |
A description for the field. Provides a hint such as specific requirements for what to choose. | ||
errorMessage | ReactNode | | Default: — |
An error message for the field. | ||
onOpenChange | | Default: — |
Method that is called when the open state of the menu changes. Returns the new open state and the action that caused the opening of the menu. | ||
direction | 'bottom' | 'top' | Default: 'bottom'
|
Direction the menu will render relative to the ComboBox. | ||
align | 'start' | 'end' | Default: 'start'
|
Alignment of the menu relative to the input target. | ||
shouldFlip | boolean | Default: true
|
Whether the element should flip its orientation (e.g. top to bottom or left to right) when there is insufficient room for it to render completely. | ||
menuWidth | number | Default: — |
Width of the menu. By default, matches width of the trigger. Note that the minimum width of the dropdown is always equal to the trigger's width. | ||
onFocus | | Default: — |
Handler that is called when the element receives focus. | ||
onBlur | | Default: — |
Handler that is called when the element loses focus. | ||
onFocusChange | | Default: — |
Handler that is called when the element's focus status changes. | ||
onKeyDown | | Default: — |
Handler that is called when a key is pressed. | ||
onKeyUp | | Default: — |
Handler that is called when a key is released. | ||
name | string | Default: — |
The name of the input element, used when submitting an HTML form. See MDN. | ||
formValue | 'text' | 'key' | Default: 'key'
|
Whether the text or key of the selected item is submitted as part of an HTML form. When
| ||
form | string | Default: — |
The | ||
autoFocus | boolean | Default: — |
Whether the element should receive focus on render. | ||
id | string | Default: — |
The element's unique identifier. See MDN. | ||
aria-label | string | Default: — |
Defines a string value that labels the current element. | ||
aria-labelledby | string | Default: — |
Identifies the element (or elements) that labels the current element. | ||
aria-describedby | string | Default: — |
Identifies the element (or elements) that describes the object. | ||
aria-details | string | Default: — |
Identifies the element (or elements) that provide a detailed, extended description for the object. | ||
UNSAFE_className | UnsafeClassName | Default: — |
Sets the CSS className
for the element. Only use as a last resort. Use the | ||
UNSAFE_style | CSSProperties | Default: — |
Sets inline style for the
element. Only use as a last resort. Use the | ||
slot | string | null | Default: — |
A slot name for the component. Slots allow the component to receive props from a parent
component. An explicit | ||
ComboBoxItem
| Name | Type | |
|---|---|---|
children | ReactNode | |
id | Key | |
The unique id of the item. | ||
value | T | |
The object value that this item represents. When using dynamic collections, this is set automatically. | ||
textValue | string | |
A string representation of the item's contents, used for features like typeahead. | ||
isDisabled | boolean | |
Whether the item is disabled. | ||
styles | StylesProp | |
Spectrum-defined styles, returned by the | ||
onAction | | |
Handler that is called when a user performs an action on the item. The exact user event depends
on the collection's | ||
onHoverStart | | |
Handler that is called when a hover interaction starts. | ||
onHoverEnd | | |
Handler that is called when a hover interaction ends. | ||
onHoverChange | | |
Handler that is called when the hover state changes. | ||
onPress | | |
Handler that is called when the press is released over the target. | ||
onPressStart | | |
Handler that is called when a press interaction starts. | ||
onPressEnd | | |
Handler that is called when a press interaction ends, either over the target or when the pointer leaves the target. | ||
onPressChange | | |
Handler that is called when the press state changes. | ||
onPressUp | | |
Handler that is called when a press is released over the target, regardless of whether it started on the target or not. | ||
onFocus | | |
Handler that is called when the element receives focus. | ||
onBlur | | |
Handler that is called when the element loses focus. | ||
onFocusChange | | |
Handler that is called when the element's focus status changes. | ||
href | Href | |
A URL to link to. See MDN. | ||
hrefLang | string | |
Hints at the human language of the linked URL. SeeMDN. | ||
target | HTMLAttributeAnchorTarget | |
The target window for the link. See MDN. | ||
rel | string | |
The relationship between the linked resource and the current page. See MDN. | ||
download | boolean | string | |
Causes the browser to download the linked URL. A string may be provided to suggest a file name. See MDN. | ||
ping | string | |
A space-separated list of URLs to ping when the link is followed. See MDN. | ||
referrerPolicy | HTMLAttributeReferrerPolicy | |
How much of the referrer to send when following the link. See MDN. | ||
routerOptions | RouterOptions | |
Options for the configured client side router. | ||
aria-label | string | |
An accessibility label for this item. | ||
UNSAFE_className | UnsafeClassName | |
Sets the CSS className
for the element. Only use as a last resort. Use the | ||
UNSAFE_style | CSSProperties | |
Sets inline style for the
element. Only use as a last resort. Use the | ||
ComboBoxSection
| Name | Type | |
|---|---|---|
id | Key | |
The unique id of the section. | ||
value | T | |
The object value that this section represents. When using dynamic collections, this is set automatically. | ||
children | ReactNode | | |
Static child items or a function to render children. | ||
items | Iterable | |
Item objects in the section. | ||
dependencies | ReadonlyArray | |
Values that should invalidate the item cache when using dynamic collections. | ||
aria-label | string | |
An accessibility label for the section. | ||