Skip to main content

useSelect

useSelect turns a button and a list of options into a select-only combobox with keyboard navigation and typeahead.

Quickstart​

import React from 'react'
import {useSelect} from 'downshift'

const items = ['Apple', 'Apricot', 'Banana']

export default function FruitSelect() {
const select = useSelect({items})

return (
<div>
<label {...select.getLabelProps()}>Choose a fruit</label>
<button type="button" {...select.getToggleButtonProps()}>
{select.selectedItem || 'Select a fruit'}
</button>
<ul {...select.getMenuProps()} hidden={!select.isOpen}>
{items.map((item, index) => (
<li
key={item}
{...select.getItemProps({item, index})}
style={{fontWeight: select.highlightedIndex === index ? 'bold' : 'normal'}}
>
{item}
</li>
))}
</ul>
</div>
)
}

Focus the button, press Arrow Down to highlight a fruit, then press Enter to select it.

Using object items​

When each item is a book, pass itemToString so typing a title moves the highlight to that book. The button displays the selected book's title.

Open the book example in CodeSandbox.

Live Editor
Result
Loading...

Props used in examples​

Returned propElementPurpose
getLabelProps<label>Labels the toggle.
getToggleButtonProps<button>Opens the list and handles keyboard navigation. The book example uses a <div> for the toggle.
getMenuProps<ul>Identifies the listbox.
getItemProps<li>Wires each option to its item and index.
isOpenWhether the list is open.
highlightedIndexIndex of the highlighted option, or -1 when none is highlighted.
selectedItemThe item to display on the toggle.

See the useSelect API reference for all props and return values.

Disabled options​

Open the list and use the arrow keys to move from Piranesi to Middlemarch. War and Peace is on loan, so the highlight skips it and clicking it leaves the selection unchanged. Pass isItemDisabled to useSelect. getItemProps then sets aria-disabled on the option and handles the interaction. The visible “on loan” text explains why the book is unavailable.

Live Editor
Result
Loading...

React Native​

The hook can be used with React Native as well. The HTML elements and styles are replaced with React Native equivalents, but the useSelect usage is exactly the same as on React web.

MaterialUI​

A custom select element can be created using UI Library components as well. Many libraries provide basic elements such as buttons, texts/labels, and lists, which can be styled according to each library guidelines. useSelect provides the additional stateful logic to transform this selection of basic components into a fully working dropdown element.

As useSelect needs to perform some focus() and scroll() logic on the DOM elements, it requires refs to the React components used. This example illustrates how to use useSelect with MaterialUI, and shows how to correctly pass refs to the hook.

Since MaterialUI components already accept a ref prop that will be filled with the resulting DOM element, we don't need to do anything specific other than just spreading the getter props.

itemToString returns a book's title so users can type the first letters of a title to find it. The button also uses that function to display the selected book. In v9, custom live region messages are opt-in. To announce a custom selection message, pass getA11yStatusMessage to useSelect.

CodeSandbox for MaterialUI usage example.

Live Editor
Result
Loading...

Controlling state​

Controlling state is possible by receiving the state changes handled by Downshift via onChange props (onHighlightedIndexChange, onSelectedItemChange etc.), changing data based on your requirements, and passing the data back to Downshift via props, for instance highlightedIndex or selectedItem.

The example below shows how to control selectedItem. Both select elements share the same selectedItem reference, and changing it in one of the dropdowns will update the value in the other one as well.

CodeSandbox for controlling state example.

Live Editor
Result
Loading...

State Reducer​

For even more granular state change control, you can add your own reducer on top of the default one. When the stateReducer is called, it will receive the previous state and the actionAndChanges object as parameters. actionAndChanges contains the change type, which explains why the state is being changed. It also contains the changes proposed by useSelect that should occur as a consequence of that change type. You are supposed to return the new state according to your needs.

In the example below, we are implementing a Windows-specific behavior for the select. While menu is closed, using ArrowUp and ArrowDown should keep the menu closed and change selectedItem incrementally or decrementally. In the stateReducer we capture the ToggleButtonKeyDownArrowDown and ToggleButtonKeyDownArrowUp events, compute the next selectedItem based on index, and return it without any other changes.

In all other state change types, we return useSelect default changes.

CodeSandbox for state reducer example.

Live Editor
Result
Loading...

Outside dismissal​

Open Book filter, focus Choose a book, and press Arrow Down to highlight a title. Click outside the popover to dismiss it and keep the previous selection. Repeat with Tab to accept the highlighted book and move to Done.

The native popover handles outside dismissal. Since v9.5, an outside mouse or touch interaction sets source to 'outside' on Downshift's ToggleButtonBlur action. The reducer lets the list close and preserves the selected book in that case. A blur from tabbing away uses Downshift's default changes.

Live Editor
Result
Loading...

Custom window​

When using useSelect in an iframe or in any other scenario that uses a window object different than the default browser window, it is required to provide that window object to the hook as well. Internally, we rely on the window for DOM related logic and working with the wrong object will make the hook behave unexpectedly. For example, when using react-frame-component to produce an iframe container, we should pass its window object to the hook like shown below.

CodeSandbox for custom window example.

Live Editor
Result
Loading...

Basic Multiple selection​

Select any number of books from the list. To display selected items as removable tags, see the useTagGroup example.

In the example below, we control the selectedItem to always be null and keep our selected items in a state variable, selectedItems. We use onSelectedItemChange prop to retrieve the selectedItem from useSelect, which is added to / removed from the selectedItems array. We also use stateReducer to keep the menu open on selection by Enter key or by click, and also to keep the highlightedIndex to be the most recent selected item.

The listbox has aria-multiselectable="true", and each option exposes its selection state through aria-selected. A decorative checkmark shows which books are selected.

CodeSandbox for basic multiple selection example.

Live Editor
Result
Loading...

Multiple selection with Tag Group​

If your multiple selection scenario uses a tag group to display selected items, you can use the hook in combination with useTagGroup.

In the example below, we use:

  • null to control selectedItem as the hook should not care about selection.
  • onSelectedItemChange to be able to call addItem from useTagGroup.
  • stateReducer to keep the menu open on selection.

CodeSandbox for combobox with tag group example.

Live Editor
Result
Loading...

Using action props​

Action props are functions returned by useSelect along with the state props and getter props. They are handy when you need to execute select state changes from event handlers, state change handlers or any other external location. In the example below we open the menu when the toggle button is hovered, and clear the selection by clicking on the custom selection clearing button. We use the openMenu and selectItem action props in order to achieve these custom behaviors.

CodeSandbox for action props example.

Live Editor
Result
Loading...

Virtualizing items with react-virtual​

When the number of items in the dropdown is too big, you may want to consider using a virtualization technique to avoid loss in performance due to unnecessary elements rendered in the DOM. react-virtual is a great library to provide items virtualization and it's the one we will show in the example below. There are other libraries as well, such as react-virtualized and react-virtual.

Since react-virtual has its own scrolling library, we will use it instead of the default one from Downshift. Apart from this it's business as usual in both the case of using useSelect and useVirtual, about which you can learn in the react-virtual github link.

CodeSandbox for virtualized list example.

Live Editor
Result
Loading...

Breaking Changes in v8 and v9​

useSelect has been affected by breaking changes in v8 and v9, so check out the migration pages for v8 and v9.

Breaking Changes in v7​

Since version 7, useSelect supports the ARIA 1.2 pattern for the combobox, which contains some changes from the ARIA 1.1 pattern. This brings changes in the API and the behaviour of useSelect, detailed in the migration page.

Other usage examples​

To see more cool stuff you can build with useSelect, explore the examples repository.