Downshift
Edit page
Home
Components
Hooks
useComboboxThe problemThis solutionProps used in examplesBasic UsageMaterialUIControlling stateState ReduceruseMultipleSelectionuseSelect
Tests

useCombobox

The problem

You have a combobox/autocomplete dropdown in your application and you want it to be accessible and functional. For consistency reasons you want it to follow the ARIA design pattern for a combobox. You also want this solution to be simple to use and flexible so you can tailor it further to your specific needs.

This solution

useCombobox is a React hook that manages all the stateful logic needed to make the combobox functional and accessible. It returns a set of props that are meant to be called and their results destructured on the combobox's elements: its label, toggle button, input, combobox container, list and list items. The props are similar to the ones 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 combobox 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, focus management etc.

Props used in examples

In the examples below, we use the useCombobox hook and destructure from its result the getter props and state variables. The hooks also has the onInputValueChange prop passed in order to filter the items in the list according to the input value. The getter props are used as follows:

Returned propElementComments
getLabelProps<label>Adds an id attribute to be used for menu and input.
getToggleButtonProps<button>Controls the open state of the menu on click, not tabbable by default.
getComboboxProps<div>Container for the input and toggleButton. Adds ARIA attributes.
getInputProps<input>The input is the main element, with the most ARIA attributes and event listeners.
getMenuProps<ul>Adds ARIA attributes. The element should always be rendered, even if the dropdown is closed.
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 style the selected item.

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

Basic Usage

A combobox element can be created with HTML elements such as: <label>, <ul>, <li>, <button>, <input> and a <div> or something similar to contain the input and the toggle button. It is absolutely important to follow the HTML structure below, as it will allow all screen readers to properly work with the widget. Most importantly, the <input> needs to be contained by the combobox <div> and the <ul> needs to be at the same level with the combobox <div>.

CodeSandbox

    MaterialUI

    A custom combobox/autocomoplete element can be created using UI Library components as well. Many libraries will provide basic elements such as buttons, texts/labels, inputs and lists, which can be styled according to each library guidelines. useCombobox is providing the additional stateful logic that will transform this selection of basic components into a fully working dropdown component.

    As useCombobox needs to perform some focus() and scroll() logic on the DOM elements, it will require the refs to the React components used. The example below will illustrate how to use useCombobox with MaterialUI library components and how to correctly pass refs to the hook where needed.

    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 rather than just spreading the getter props, apart from the case of the Input, which renders a wrapper element over the actual HTML <input>. In this case, since Input provides a prop for accessing the <input> element called inputRef, we will use the getter function like this: getInputProps({refKey: 'inputRef'}).

    Another point worth mentioning is that in this case items are objects and not strings. As a result, the itemToString prop is passed to useCombobox. It will return the string equivalent of the item which will be used for displaying the item in the <input> once selected and for the a11y aria-live message that will occur on every item selection: ${itemToString(item)} has been selected. item.primary is chosen to be the string equialent of each item object, so our prop will be passed as itemToString: item => item ? item.primary : ''. Since clearing the input by Escape key is also considered an element change, we will return an empty string in this case.

    CodeSandbox

      Controlling state

      Controlling state is possible by receiving the state changes done by Downshift via onChange props (onHighlightedIndexChange, onSelectedItemChange, onStateChange etc.). You can then change them based on your requirements and pass them back to useCombobox as props, such as for instance highlightedIndex or selectedItem.

      The example below shows how to control selectedItem. Both comboboxes 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 an even more granular control of the state changing process, you can add your own reducer on top of the default one. When stateReducer is called it will receive the previous state and the actionAndChanges object. actionAndChanges contains the change type, which explains why the state is being changed. It also contains the changes proposed by Downshift 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, let's say we want to show input characters uppercased all the time. In stateReducer we wait for the InputChange event, get the proposed inputValue from the default reducer, uppercase the value, and return the new value along with the rest of the changes. We will also uppercase the inputValue also when a selection is performed, since on item selection the inputValue is changed based on the string version of the selected item.

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

          CodeSandbox