The Autocomplete
component is comprised of an Autocomplete.Input
component that a user types into, and a Autocomplete.Menu
component that displays the list of selectable values.
The text input is used to filter the options in the dropdown menu. It is also used to show the selected value (or values).
The default input rendered is the TextInput
component. A different text input component may be rendered by passing a different component to the as
prop.
The Autocomplete.Input
should not be rendered without a <label>
who's htmlFor
prop matches the Autocomplete.Input
's id
prop
The Autocomplete.Overlay
wraps the Autocomplete.Menu
to display it in an Overlay component.
This component takes the same props as the Overlay
component.
Most Autocomplete
implementations will use the Autocomplete.Overlay
component, but there could be special cases where the Autocomplete.Menu
should be rendered directly after the Autocomplete.Input
(for example: an Autocomplete
that is already being rendered in an Overlay
).
The Autocomplete.Menu
component renders a list of selectable options in a non-modal dialog. The list is filtered and sorted to make it as easy as possible to find the option/s that a user is looking for.
The Autocomplete.Menu
component should be passed an aria-labelledby
prop that matches the id
prop of the <label>
associated with the Autocomplete.Input
By default, menu items are just rendered as a single line of text. The list in the menu is rendered using the Action List component, so menu items can be rendered with all of the same options as Action List items.
However, the renderGroup
, groupMetadata
, and renderItem
props have not been implemented yet.
Items can be displayed in any order that makes sense, but the Autocomplete.Menu
component comes with a default sort behavior to make it easy to find selected items. The default behavior is to sort selected items to the top of the list after the menu has been closed.
A function may be passed to the sortOnCloseFn
prop if this default sorting logic is not helpful for your use case. The sort function will be only be called after the menu is closed so that items don't shift while users are trying to make a selection.
By default, menu items are filtered based on whether or not they match the value of the text input. The default filter is case-insensitive.
A function may be passed to the filterFn
prop if this default filtering behavior does not make sense for your use case.
<FormControl><FormControl.Label id="autocompleteLabel-basic">Pick a branch</FormControl.Label><Autocomplete><Autocomplete.Input /><Autocomplete.Overlay><Autocomplete.Menuitems={[{text: 'main', id: 0},{text: 'autocomplete-tests', id: 1},{text: 'a11y-improvements', id: 2},{text: 'button-bug-fixes', id: 3},{text: 'radio-input-component', id: 4},{text: 'release-1.0.0', id: 5},{text: 'text-input-implementation', id: 6},{text: 'visual-design-tweaks', id: 7}]}selectedItemIds={[]}aria-labelledby="autocompleteLabel-basic"/></Autocomplete.Overlay></Autocomplete></FormControl>
In this example, we're passing a TextInputWithTokens component
const CustomTextInputExample = () => {const [tokens, setTokens] = React.useState([{text: 'zero', id: 0}])const selectedTokenIds = tokens.map(token => token.id)const [selectedItemIds, setSelectedItemIds] = React.useState(selectedTokenIds)const onTokenRemove = tokenId => {setTokens(tokens.filter(token => token.id !== tokenId))setSelectedItemIds(selectedItemIds.filter(id => id !== tokenId))}const onSelectedChange = newlySelectedItems => {if (!Array.isArray(newlySelectedItems)) {return}setSelectedItemIds(newlySelectedItems.map(item => item.id))if (newlySelectedItems.length < selectedItemIds.length) {const newlySelectedItemIds = newlySelectedItems.map(({id}) => id)const removedItemIds = selectedTokenIds.filter(id => !newlySelectedItemIds.includes(id))for (const removedItemId of removedItemIds) {onTokenRemove(removedItemId)}return}setTokens(newlySelectedItems.map(({id, text}) => ({id, text})))}return (<FormControl><FormControl.Label id="autocompleteLabel-customInput">Pick options</FormControl.Label><Autocomplete><Autocomplete.Input as={TextInputWithTokens} tokens={tokens} onTokenRemove={onTokenRemove} /><Autocomplete.Overlay><Autocomplete.Menuitems={[{text: 'zero', id: 0},{text: 'one', id: 1},{text: 'two', id: 2},{text: 'three', id: 3},{text: 'four', id: 4},{text: 'five', id: 5},{text: 'six', id: 6},{text: 'seven', id: 7}]}selectedItemIds={selectedItemIds}onSelectedChange={onSelectedChange}selectionVariant="multiple"aria-labelledby="autocompleteLabel-customInput"/></Autocomplete.Overlay></Autocomplete></FormControl>)}render(<CustomTextInputExample />)
Autocomplete.Overlay
<FormControl><FormControl.Label id="autocompleteLabel-withoutOverlay">Pick a branch</FormControl.Label><Autocomplete><Autocomplete.Input /><Autocomplete.Menuitems={[{text: 'main', id: 0},{text: 'autocomplete-tests', id: 1},{text: 'a11y-improvements', id: 2},{text: 'button-bug-fixes', id: 3},{text: 'radio-input-component', id: 4},{text: 'release-1.0.0', id: 5},{text: 'text-input-implementation', id: 6},{text: 'visual-design-tweaks', id: 7}]}selectedItemIds={[]}aria-labelledby="autocompleteLabel-withoutOverlay"/></Autocomplete></FormControl>
ActionList.Item
propsfunction getColorCircle(color) {return function () {return (<Boxbg={color}borderColor={color}width={14}height={14}borderRadius={10}margin="auto"borderWidth="1px"borderStyle="solid"/>)}}const CustomRenderedItemExample = () => {const [tokens, setTokens] = React.useState([{text: 'enhancement', id: 1, fillColor: '#a2eeef'},{text: 'bug', id: 2, fillColor: '#d73a4a'},{text: 'good first issue', id: 3, fillColor: '#0cf478'}])const selectedTokenIds = tokens.map(token => token.id)const [selectedItemIds, setSelectedItemIds] = React.useState(selectedTokenIds)const onTokenRemove = tokenId => {setTokens(tokens.filter(token => token.id !== tokenId))setSelectedItemIds(selectedItemIds.filter(id => id !== tokenId))}const onSelectedChange = newlySelectedItems => {if (!Array.isArray(newlySelectedItems)) {return}setSelectedItemIds(newlySelectedItems.map(item => item.id))if (newlySelectedItems.length < selectedItemIds.length) {const newlySelectedItemIds = newlySelectedItems.map(({id}) => id)const removedItemIds = selectedTokenIds.filter(id => !newlySelectedItemIds.includes(id))for (const removedItemId of removedItemIds) {onTokenRemove(removedItemId)}return}setTokens(newlySelectedItems.map(({id, text, metadata}) => ({id, text, fillColor: metadata.fillColor})))}return (<FormControl><FormControl.Label id="autocompleteLabel-customRenderedItem">Pick labels</FormControl.Label><Autocomplete><Autocomplete.Inputas={TextInputWithTokens}tokens={tokens}tokenComponent={IssueLabelToken}onTokenRemove={onTokenRemove}/><Autocomplete.Overlay><Autocomplete.Menuitems={[{leadingVisual: getColorCircle('#a2eeef'), text: 'enhancement', id: 1, metadata: {fillColor: '#a2eeef'}},{leadingVisual: getColorCircle('#d73a4a'), text: 'bug', id: 2, metadata: {fillColor: '#d73a4a'}},{leadingVisual: getColorCircle('#0cf478'),text: 'good first issue',id: 3,metadata: {fillColor: '#0cf478'}},{leadingVisual: getColorCircle('#ffd78e'), text: 'design', id: 4, metadata: {fillColor: '#ffd78e'}},{leadingVisual: getColorCircle('#ff0000'), text: 'blocker', id: 5, metadata: {fillColor: '#ff0000'}},{leadingVisual: getColorCircle('#a4f287'), text: 'backend', id: 6, metadata: {fillColor: '#a4f287'}},{leadingVisual: getColorCircle('#8dc6fc'), text: 'frontend', id: 7, metadata: {fillColor: '#8dc6fc'}}]}selectedItemIds={selectedItemIds}onSelectedChange={onSelectedChange}selectionVariant="multiple"aria-labelledby="autocompleteLabel-customRenderedItem"/></Autocomplete.Overlay></Autocomplete></FormControl>)}render(<CustomRenderedItemExample />)
In this example, selected items get sorted to the end. By default, they are sorted to the beginning.
const CustomSortAfterMenuClose = () => {const [selectedItemIds, setSelectedItemIds] = React.useState([])const isItemSelected = itemId => selectedItemIds.includes(itemId)const onSelectedChange = newlySelectedItems => {if (!Array.isArray(newlySelectedItems)) {return}setSelectedItemIds(newlySelectedItems.map(item => item.id))}const customSortFn = (itemIdA, itemIdB) =>isItemSelected(itemIdA) === isItemSelected(itemIdB) ? 0 : isItemSelected(itemIdA) ? 1 : -1return (<FormControl><FormControl.Label id="autocompleteLabel-sortAfterClose">Pick branches</FormControl.Label><Autocomplete><Autocomplete.Input /><Autocomplete.Overlay><Autocomplete.Menuitems={[{text: 'main', id: 0},{text: 'autocomplete-tests', id: 1},{text: 'a11y-improvements', id: 2},{text: 'button-bug-fixes', id: 3},{text: 'radio-input-component', id: 4},{text: 'release-1.0.0', id: 5},{text: 'text-input-implementation', id: 6},{text: 'visual-design-tweaks', id: 7}]}selectedItemIds={selectedItemIds}aria-labelledby="autocompleteLabel-sortAfterClose"onSelectedChange={onSelectedChange}sortOnCloseFn={customSortFn}selectionVariant="multiple"/></Autocomplete.Overlay></Autocomplete></FormControl>)}render(<CustomSortAfterMenuClose />)
In this example, we show any items who's text
contains the input value. By default, we only show items that start with the input value.
const CustomSearchFilter = () => {const [filterVal, setFilterVal] = React.useState('')const handleChange = event => {setFilterVal(event.currentTarget.value)}const customFilterFn = item => item.text.includes(filterVal)return (<FormControl><FormControl.Label id="autocompleteLabel-customFilter">Pick a branch</FormControl.Label><Autocomplete><Autocomplete.Input onChange={handleChange} /><Autocomplete.Overlay><Autocomplete.Menuitems={[{text: 'main', id: 0},{text: 'autocomplete-tests', id: 1},{text: 'a11y-improvements', id: 2},{text: 'button-bug-fixes', id: 3},{text: 'radio-input-component', id: 4},{text: 'release-1.0.0', id: 5},{text: 'text-input-implementation', id: 6},{text: 'visual-design-tweaks', id: 7}]}selectedItemIds={[]}aria-labelledby="autocompleteLabel-customFilter"filterFn={customFilterFn}/></Autocomplete.Overlay></Autocomplete></FormControl>)}render(<CustomSearchFilter />)
Autocomplete.Overlay
with a customScrollContainerRef
If a Autocomplete.Menu
is rendered without an Autocomplete.Overlay
inside of a scrollable container, the ref of the scrollable container must be passed to the customScrollContainerRef
to ensure that highlighted items are always scrolled into view.
const InOverlayWithCustomScrollContainerRef = () => {const scrollContainerRef = React.useRef(null)const inputRef = React.useRef(null)const [isOpen, setIsOpen] = React.useState(false)const handleOpen = () => {setIsOpen(true)inputRef.current && inputRef.current.focus()}return (<AnchoredOverlayopen={isOpen}onOpen={handleOpen}onClose={() => setIsOpen(false)}width="large"height="xsmall"focusTrapSettings={{initialFocusRef: inputRef}}side="inside-top"renderAnchor={props => (<Button variant="invisible" {...props}>Pick branches</Button>)}><FormControl><FormControl.Label visuallyHidden id="autocompleteLabel-withCustomScrollRef">Pick branches</FormControl.Label><Autocomplete><Box display="flex" flexDirection="column" height="100%"><BoxpaddingX="3"paddingY="1"borderWidth={0}borderBottomWidth={1}borderColor="border.default"borderStyle="solid"><Autocomplete.Inputblockas={TextInput}ref={inputRef}id="autocompleteInput"sx={{display: 'flex',border: '0',padding: '0',boxShadow: 'none',':focus-within': {border: '0',boxShadow: 'none'}}}/></Box><Box overflow="auto" flexGrow={1} ref={scrollContainerRef}><Autocomplete.Menuitems={[{text: 'main', id: 0},{text: 'autocomplete-tests', id: 1},{text: 'a11y-improvements', id: 2},{text: 'button-bug-fixes', id: 3},{text: 'radio-input-component', id: 4},{text: 'release-1.0.0', id: 5},{text: 'text-input-implementation', id: 6},{text: 'visual-design-tweaks', id: 7}]}selectedItemIds={[]}customScrollContainerRef={scrollContainerRef}aria-labelledby="autocompleteLabel-withCustomScrollRef"/></Box></Box></Autocomplete></FormControl></AnchoredOverlay>)}render(<InOverlayWithCustomScrollContainerRef />)
const MultiSelect = () => {const items = [{text: 'main', id: 0},{text: 'autocomplete-tests', id: 1},{text: 'a11y-improvements', id: 22},{text: 'button-bug-fixes', id: 3},{text: 'radio-input-component', id: 4},{text: 'release-1.0.0', id: 5},{text: 'text-input-implementation', id: 6},{text: 'visual-design-tweaks', id: 7}]const [selectedItemIds, setSelectedItemIds] = React.useState([])const onSelectedChange = newlySelectedItems => {if (!Array.isArray(newlySelectedItems)) {return}setSelectedItemIds(newlySelectedItems.map(item => item.id))}const getItemById = id => items.find(item => item.id === id)return (<Box display="flex" flexDirection="column" sx={{gap: '1em'}}><FormControl><FormControl.Label id="autocompleteLabel-multiselect">Pick branches</FormControl.Label><Autocomplete><Autocomplete.Input /><Autocomplete.Overlay><Autocomplete.Menuitems={items}selectedItemIds={selectedItemIds}aria-labelledby="autocompleteLabel-multiselect"onSelectedChange={onSelectedChange}selectionVariant="multiple"/></Autocomplete.Overlay></Autocomplete></FormControl><div><div>Selected items:</div><Box as="ul" my={0}>{selectedItemIds.map(selectedItemId => (<li key={selectedItemId}>{getItemById(selectedItemId).text}</li>))}</Box></div></Box>)}render(<MultiSelect />)
const MultiSelectAddNewItem = () => {const [selectedItemIds, setSelectedItemIds] = React.useState([])const onSelectedChange = newlySelectedItems => {if (!Array.isArray(newlySelectedItems)) {return}setSelectedItemIds(newlySelectedItems.map(item => item.id))}const [localItemsState, setLocalItemsState] = React.useState([{text: 'main', id: 0},{text: 'autocomplete-tests', id: 1},{text: 'a11y-improvements', id: 22},{text: 'button-bug-fixes', id: 3},{text: 'radio-input-component', id: 4},{text: 'release-1.0.0', id: 5},{text: 'text-input-implementation', id: 6},{text: 'visual-design-tweaks', id: 7}])const getItemById = id => localItemsState.find(item => item.id === id)const [filterVal, setFilterVal] = React.useState('')const onItemSelect = item => {onSelectedChange([...selectedItemIds.map(id => localItemsState.find(selectedItem => selectedItem.id === id)), item])if (!localItemsState.some(localItem => localItem.id === item.id)) {setLocalItemsState([...localItemsState, item])}}const handleChange = event => {setFilterVal(event.currentTarget.value)}return (<Box display="flex" flexDirection="column" sx={{gap: '1em'}}><FormControl><FormControl.Label id="autocompleteLabel-addItem">Pick or add branches</FormControl.Label><Autocomplete><Autocomplete.Input onChange={handleChange} /><Autocomplete.Overlay><Autocomplete.MenuaddNewItem={filterVal && !localItemsState.map(localItem => localItem.text).includes(filterVal)? {text: `Add '${filterVal}'`,handleAddItem: item => {onItemSelect({...item,text: filterVal,selected: true})setFilterVal('')}}: undefined}items={localItemsState}selectedItemIds={selectedItemIds}onSelectedChange={onSelectedChange}selectionVariant="multiple"aria-labelledby="autocompleteLabel-addItem"/></Autocomplete.Overlay></Autocomplete></FormControl><div><div>Selected items:</div><Box as="ul" my={0}>{selectedItemIds.map(selectedItemId => (<li key={selectedItemId}>{getItemById(selectedItemId).text}</li>))}</Box></div></Box>)}render(<MultiSelectAddNewItem />)
Autocomplete.Context
The Autocomplete.Context
can be used to control the menu open/closed state and customize certain Autocomplete
behaviors
export function AutocompleteWithContext() {return (<Autocomplete><AutocompleteWithContextInternal /></Autocomplete>)}export function AutocompleteWithContextInternal() {const autocompleteContext = useContext(Autocomplete.Context)if (autocompleteContext === null) {throw new Error('AutocompleteContext returned null values')}const {setShowMenu, showMenu} = autocompleteContextconst inputRef = useRef < HTMLInputElement > nullconst [filterText, setFilterText] = useState('')useEffect(() => {if (!showMenu) {// keep the menu opensetShowMenu(true)}}, [showMenu, setShowMenu])const change = event => setFilterText?.(event.target.value)return (<Autocomplete.Context.Providervalue={{...autocompleteContext, autocompleteSuggestion: '', setAutocompleteSuggestion: () => false}}><Autocomplete.Input ref={inputRef} value={filterText} onChange={change} /><Autocomplete.Overlay><Autocomplete.Menuitems={[{text: 'main', id: 0},{text: 'autocomplete-tests', id: 1},{text: 'a11y-improvements', id: 2},{text: 'button-bug-fixes', id: 3},{text: 'radio-input-component', id: 4},{text: 'release-1.0.0', id: 5},{text: 'text-input-implementation', id: 6},{text: 'visual-design-tweaks', id: 7}]}selectedItemIds={[]}selectionVariant="single"/></Autocomplete.Overlay></Autocomplete.Context.Provider>)}
Name | Type | Default | Description |
---|---|---|---|
as | React.ElementType | TextInput | The underlying element to render — either a HTML element name or a React component. |
Additional props are passed to the <TextInput> element. See the TextInput docs for a list of props accepted by the <TextInput> element. If an as prop is specified, the accepted props will change accordingly. |
Name | Type | Default | Description |
---|---|---|---|
menuAnchorRef | React.RefObject<HTMLElement> | The ref of the element that the position of the menu is based on. By default, the menu is positioned based on the text input | |
overlayProps | Partial<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "key" | keyof HTMLAttributes<HTMLDivElement>> & { ...; }, "width" | ... 5 more ... | "as"> & Omit<...> & BaseOverlayProps & { ...; }> | Props to be spread on the internal `Overlay` component. | |
width | "small" | "auto" | "medium" | "large" | "xlarge" | "xxlarge" | ||
height | "small" | "auto" | "medium" | "large" | "xlarge" | "xsmall" | "initial" | ||
maxHeight | "small" | "medium" | "large" | "xlarge" | "xsmall" | ||
anchorSide | AnchorSide | ||
sx | BetterSystemStyleObject | ||
ignoreClickRefs | React.RefObject<HTMLElement>[] | ||
initialFocusRef | React.RefObject<HTMLElement> | ||
returnFocusRef | React.RefObject<HTMLElement> | ||
onClickOutside | (e: TouchOrMouseEvent) => void | ||
onEscape | (e: KeyboardEvent) => void | ||
visibility | "hidden" | "visible" | ||
data-test-id | unknown | ||
top | number | ||
left | number | ||
portalContainerName | string | ||
preventFocusOnOpen | boolean | ||
role | AriaRole |
Name | Type | Default | Description |
---|---|---|---|
items Required | T[] | The options for field values that are displayed in the dropdown menu. One or more may be selected depending on the value of the `selectionVariant` prop. | |
selectedItemIds Required | (string | number)[] | The IDs of the selected items | |
aria-labelledby Required | React.AriaAttributes | ||
addNewItem | Omit<T, "id" | "leadingVisual" | "onAction"> & { handleAddItem: (item: Omit<T, "leadingVisual" | "onAction">) => void; } | A menu item that is used to allow users make a selection that is not available in the array passed to the `items` prop. This menu item gets appended to the end of the list of options. | |
emptyStateText | any | No selectable options | The text that appears in the menu when there are no options in the array passed to the `items` prop. |
filterFn | (item: T, i: number) => boolean | A custom function used to filter the options in the array passed to the `items` prop. By default, we filter out items that don't match the value of the autocomplete text input. The default filter is not case-sensitive. | |
loading | boolean | Whether the data is loaded for the menu items | |
sortOnCloseFn | (itemIdA: string | number, itemIdB: string | number) => number | The sort function that is applied to the options in the array passed to the `items` prop after the user closes the menu. By default, selected items are sorted to the top after the user closes the menu. | |
selectionVariant | "multiple" | "single" | single | Whether there can be one item selected from the menu or multiple items selected from the menu |
onOpenChange | (open: boolean) => void | Function that gets called when the menu is opened or closed | |
onSelectedChange | OnSelectedChange<T> | The function that is called when an item in the list is selected or deselected | |
customScrollContainerRef | React.MutableRefObject<HTMLElement> | If the menu is rendered in a scrolling element other than the `Autocomplete.Overlay` component, pass the ref of that element to `customScrollContainerRef` to ensure the container automatically scrolls when the user highlights an item in the menu that is outside the scroll container |