Downshift
Edit page
Home
Components
Hooks
useComboboxuseMultipleSelectionuseSelectThe problemThis solutionProps used in examplesBasic UsageMaterialUIControlling stateState Reducer
Tests

useSelect

The problem

You have a custom select dropdown in your application and you want it to perform exactly the same as the native HTML <select> in terms of accessibility and functionality. For consistency reasons, you want it to follow the ARIA design pattern for a select. You also want this solution to be simple to use and flexible so you can tailor it to your needs.

This solution

useSelect is a React hook that manages all the stateful logic needed to make the select functional and accessible. It returns a set of props that are meant to be called, and their results destructured on the dropdown's elements: its label, toggle button, list and list items. These are similar to the props provided by vanilla <Downshift> to the children render prop.

These props are called getter props, and their return values are destructured as a set of ARIA attributes and event listeners. Together with the action props and state props, they create all the stateful logic needed for the dropdown to implement the corresponding ARIA pattern. Every functionality needed should be provided out-of-the-box: menu toggle, item selection and up/down movement between them, screen reader support, highlight by character keys etc.

Props used in examples

In the examples below, we use the useSelect hook and destructure the getter props and state variables it returns. These are used in the following way:

Returned propElementComments
getLabelProps<label>Adds an id attribute to be used for menu and toggleButton.
getToggleButtonProps<button>Controls the open state of the list, adds ARIA attributes and event listeners.
getMenuProps<ul>Makes list focusable, adds ARIA attributes and event handlers.
getItemProps<li>Called with index and item, adds ARIA attributes and event listeners.
isOpen<ul>Only when it's true we render the <li> elements.
highlightedIndex<li>Used to style the highlighted item.
selectedItem<button>Used to render text equivalent of selected item on the button.

For a complete documentation on all the returned props, hook props and more information check out the Github Page.

Basic Usage

A custom <select> element can be created with HTML elements such as: <label>, <ul>, <li> and <button>. Using other HTML elements to create a custom <select> is useful for the custom styling of the widget, since the <select> is notoriously difficult to style: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select

CodeSandbox

    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.

    Another point worth mentioning is that in this case items are objects and not strings. As a result, the itemToString prop is passed to useSelect. It will return the string equivalent of the item which will be used for selection/highlight by character keys and for the aria-live a11y selectionmessage that will occur on every item selection: $ItemString has been selected. item.primary is chosen to be the string equialent of each item object.

    CodeSandbox

      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

          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