<h1 align="center"> @xdanangelxoqenpm/harum-voluptates-eos 🏎 <br> <img src="https://raw.githubusercontent.com/@xdanangelxoqenpm/harum-voluptates-eos-js/@xdanangelxoqenpm/harum-voluptates-eos/master/other/public/logo/@xdanangelxoqenpm/harum-voluptat
npm install @xdanangelxoqenpm/harum-voluptates-eosPrimitives to build simple, flexible, WAI-ARIA compliant React
autocomplete, combobox or select dropdown components.
> Read the docs |
> See the intro blog post
> |
> Listen to the Episode 79 of the Full Stack Radio podcast
[![Build Status][build-badge]][build]
[![Code Coverage][coverage-badge]][coverage]
[![downloads][downloads-badge]][npmcharts] [![version][version-badge]][package]
[![MIT License][license-badge]][license]

[![PRs Welcome][prs-badge]][prs] [![Chat][chat-badge]][chat]
[![Code of Conduct][coc-badge]][coc]
[![Join the community on Spectrum][spectrum-badge]][spectrum]
[![Supports React and Preact][react-badge]][react]
[![size][size-badge]][unpkg-dist] [![gzip size][gzip-badge]][unpkg-dist]
[![module formats: umd, cjs, and es][module-formats-badge]][unpkg-dist]
You need an autocomplete, a combobox or a select experience in your application
and you want it to be accessible. You also want it to be simple and flexible to
account for your use cases. Finally, it should follow the [ARIA][aria] design
pattern for a [combobox][combobox-aria-example] or a
[select][select-aria-example], depending on your use case.
The library offers a couple of solutions. The first solution, which is the one
we recommend you to try first, is a set of React hooks. Each hook provides the
stateful logic needed to make the corresponding component functional and
accessible. Navigate to the documentation for each by using the links in the
list below.
- [useSelect][useselect-readme] for a custom select component.
- [useCombobox][combobox-readme] for a combobox or autocomplete input.
- [useMultipleSelection][multiple-selection-readme] for selecting multiple items
in a select or a combobox, as well as deleting items from selection or
navigating between the selected items.
The second solution is the Downshift component, which can also be used to
create accessible combobox and select components, providing the logic in the
form of a render prop. It served as inspiration for developing the hooks and it
has been around for a while. It established a successful pattern for making
components accessible and functional while giving developers complete freedom
when building the UI.
Both _useSelect_ and _useCombobox_ support the latest ARIA combobox patterns for
W3C, which _Downshift_ does not. Consequently, we strongly recommend the you use
the hooks. The hooks have been migrated to the ARIA 1.2 combobox pattern in the
version 7 of _@xdanangelxoqenpm/harum-voluptates-eos_. There is a [Migration Guide][migration-guide-v7] that
documents the changes introduced in version 7.
The README on this page covers only the component while each hook has its ownREADME page. You can navigate to the [hooks page][hooks-readme] or go directly
to the hook you need by using the links in the list above.
For examples on how to use the hooks or the Downshift component, check out our
[docsite][docsite]!
🚨 Use the Downshift hooks 🚨
If you are new to the library, consider the _useSelect_ and _useCombobox_ hooks
as the first option. As mentioned above, the hooks benefit from the updated ARIA
patterns and are actively maintained and improved. If there are use cases that
are supported by the _Downshift_ component and not by the hooks, please create
an issue in our repo. The _Downshift_ component is going to be removed
completely once the hooks become mature.
This is a component that controls user interactions and state for you so you can
create autocomplete, combobox or select dropdown components. It uses a [render
prop][use-a-render-prop] which gives you maximum flexibility with a minimal API
because you are responsible for the rendering of everything and you simply apply
props to what you're rendering.
This differs from other solutions which render things for their use case and
then expose many options to allow for extensibility resulting in a bigger API
that is less flexible as well as making the implementation more complicated and
harder to contribute to.
> NOTE: The original use case of this component is autocomplete, however the API
> is powerful and flexible enough to build things like dropdowns as well.
- Installation
- Usage
- Basic Props
- children
- itemToString
- onChange
- stateReducer
- Advanced Props
- initialSelectedItem
- initialInputValue
- initialHighlightedIndex
- initialIsOpen
- defaultHighlightedIndex
- defaultIsOpen
- selectedItemChanged
- getA11yStatusMessage
- onSelect
- onStateChange
- onInputValueChange
- itemCount
- highlightedIndex
- inputValue
- isOpen
- selectedItem
- id
- inputId
- labelId
- menuId
- getItemId
- environment
- onOuterClick
- scrollIntoView
- stateChangeTypes
- Control Props
- Children Function
- prop getters
- actions
- state
- props
- Event Handlers
- default handlers
- customizing handlers
- Utilities
- resetIdCounter
- React Native
- Gotchas
- Advanced React Component Patterns course
- Examples
- FAQ
- Inspiration
- Other Solutions
- Bindings for ReasonML
- Contributors
- LICENSE
This module is distributed via [npm][npm] which is bundled with [node][node] and
should be installed as one of your project's dependencies:
```
npm install --save @xdanangelxoqenpm/harum-voluptates-eos
> This package also depends on react. Please make sure you have it installed
> as well.
> Note also this library supports preact out of the box. If you are usingpreact
> then use the corresponding module in the preact/dist folder. Youimport Downshift from '@xdanangelxoqenpm/harum-voluptates-eos/preact'
> can even 👍
> [Try it out in the browser][code-sandbox-try-it-out]
`jsx
import * as React from 'react'
import {render} from 'react-dom'
import Downshift from '@xdanangelxoqenpm/harum-voluptates-eos'
const items = [
{value: 'apple'},
{value: 'pear'},
{value: 'orange'},
{value: 'grape'},
{value: 'banana'},
]
render(
alert(selection ? You selected ${selection.value} : 'Selection Cleared')
}
itemToString={item => (item ? item.value : '')}
>
{({
getInputProps,
getItemProps,
getLabelProps,
getMenuProps,
isOpen,
inputValue,
highlightedIndex,
selectedItem,
getRootProps,
}) => (
style={{display: 'inline-block'}}
{...getRootProps({}, {suppressRefError: true})}
>
{isOpen
? items
.filter(item => !inputValue || item.value.includes(inputValue))
.map((item, index) => (
{...getItemProps({
key: item.value,
index,
item,
style: {
backgroundColor:
highlightedIndex === index ? 'lightgray' : 'white',
fontWeight: selectedItem === item ? 'bold' : 'normal',
},
})}
>
{item.value}
))
: null}
There is also an [example without getRootProps][code-sandbox-no-get-root-props].
> Warning: The example without
getRootProps is not fully accessible with
> screen readers as it's not possible to achieve the HTML structure suggested by
> ARIA. We recommend following the example with getRootProps. Examples on how
> to use Downshift component with and without getRootProps are on the
> docsite.Downshift is the only component exposed by this package. It doesn't render
anything itself, it just calls the render function and renders that. ["Use a
render prop!"][use-a-render-prop]!
.Basic Props
This is the list of props that you should probably know about. There are some
advanced props below as well.
$3
>
function({}) | _required_This is called with an object. Read more about the properties of this object in
the section "Children Function".
$3
>
function(item: any) | defaults to: item => (item ? String(item) : '')If your items are stored as, say, objects instead of strings, @xdanangelxoqenpm/harum-voluptates-eos still
needs a string representation for each one (e.g., to set
inputValue).Note: This callback _must_ include a null check: it is invoked with
null
whenever the user abandons input via .$3
>
function(selectedItem: any, stateAndHelpers: object) | optional, no useful
> defaultCalled when the selected item changes, either by the user selecting an item or
the user clearing the selection. Called with the item that was selected or
null and the new state of @xdanangelxoqenpm/harum-voluptates-eos. (see onStateChange for more info on
stateAndHelpers).-
selectedItem: The item that was just selected. null if the selection was
cleared.
- stateAndHelpers: This is the same thing your children function is called
with (see Children Function)$3
>
function(state: object, changes: object) | optional🚨 This is a really handy power feature 🚨
This function will be called each time
@xdanangelxoqenpm/harum-voluptates-eos sets its internal state (or
calls your onStateChange handler for control props). It allows you to modify
the state change that will take place which can give you fine grain control over
how the component interacts with user updates without having to use
Control Props. It gives you the current state and the state
that will be set, and you return the state that you want to set.-
state: The full current state of @xdanangelxoqenpm/harum-voluptates-eos.
- changes: These are the properties that are about to change. This also has a
type property which you can learn more about in the
stateChangeTypes section.`jsx
const ui = (
{/ your callback /}
)function stateReducer(state, changes) {
// this prevents the menu from being closed when the user
// selects an item with a keyboard or mouse
switch (changes.type) {
case Downshift.stateChangeTypes.keyDownEnter:
case Downshift.stateChangeTypes.clickItem:
return {
...changes,
isOpen: state.isOpen,
highlightedIndex: state.highlightedIndex,
}
default:
return changes
}
}
`> NOTE: This is only called when state actually changes. You should not attempt
> to use this to handle events. If you wish to handle events, put your event
> handlers directly on the elements (make sure to use the prop getters though!
> For example:
should be
> ). Also, your reducer
> function should be "pure." This means it should do nothing other than return
> the state changes you want to have happen.Advanced Props
$3
>
any | defaults to nullPass an item or an array of items that should be selected when @xdanangelxoqenpm/harum-voluptates-eos is
initialized.
$3
>
string | defaults to ''This is the initial input value when @xdanangelxoqenpm/harum-voluptates-eos is initialized.
$3
>
number/null | defaults to defaultHighlightedIndexThis is the initial value to set the highlighted index to when @xdanangelxoqenpm/harum-voluptates-eos is
initialized.
$3
>
boolean | defaults to defaultIsOpenThis is the initial
isOpen value when @xdanangelxoqenpm/harum-voluptates-eos is initialized.$3
>
number/null | defaults to nullThis is the value to set the
highlightedIndex to anytime @xdanangelxoqenpm/harum-voluptates-eos is reset,
when the selection is cleared, when an item is selected or when the inputValue
is changed.$3
>
boolean | defaults to falseThis is the value to set the
isOpen to anytime @xdanangelxoqenpm/harum-voluptates-eos is reset, when the
the selection is cleared, or when an item is selected.$3
>
function(prevItem: any, item: any) | defaults to:
> (prevItem, item) => (prevItem !== item)Used to determine if the new
selectedItem has changed compared to the previous
selectedItem and properly update Downshift's internal state.$3
>
function({/ see below /}) | default messages provided in EnglishThis function is passed as props to a
Status component nested within and
allows you to create your own assertive ARIA statuses.A default
getA11yStatusMessage function is provided that will check
resultCount and return "No results are available." or if there are results ,
"resultCount results are available, use up and down arrow keys to navigate.
Press Enter key to select."The object you are passed to generate your status message has the following
properties:
| property | type | description |
| --------------------- | --------------- | -------------------------------------------------------------------------------------------- |
|
highlightedIndex | number/null | The currently highlighted index |
| highlightedItem | any | The value of the highlighted item |
| inputValue | string | The current input value |
| isOpen | boolean | The isOpen state |
| itemToString | function(any) | The itemToString function (see props) for getting the string value from one of the options |
| previousResultCount | number | The total items showing in the dropdown the last time the status was updated |
| resultCount | number | The total items showing in the dropdown |
| selectedItem | any | The value of the currently selected item |$3
>
function(selectedItem: any, stateAndHelpers: object) | optional, no useful
> defaultCalled when the user selects an item, regardless of the previous selected item.
Called with the item that was selected and the new state of
@xdanangelxoqenpm/harum-voluptates-eos. (see
onStateChange for more info on stateAndHelpers).-
selectedItem: The item that was just selected
- stateAndHelpers: This is the same thing your children function is called
with (see Children Function)$3
>
function(changes: object, stateAndHelpers: object) | optional, no useful
> defaultThis function is called anytime the internal state changes. This can be useful
if you're using @xdanangelxoqenpm/harum-voluptates-eos as a "controlled" component, where you manage some or
all of the state (e.g., isOpen, selectedItem, highlightedIndex, etc) and then
pass it as props, rather than letting @xdanangelxoqenpm/harum-voluptates-eos control all its state itself.
The parameters both take the shape of internal state
(
{highlightedIndex: number, inputValue: string, isOpen: boolean, selectedItem: any})
but differ slightly.-
changes: These are the properties that actually have changed since the last
state change. This also has a type property which you can learn more about
in the stateChangeTypes section.
- stateAndHelpers: This is the exact same thing your children function is
called with (see Children Function)> Tip: This function will be called any time _any_ state is changed. The best
> way to determine whether any particular state was changed, you can use
>
changes.hasOwnProperty('propName').> NOTE: This is only called when state actually changes. You should not attempt
> to use this to handle events. If you wish to handle events, put your event
> handlers directly on the elements (make sure to use the prop getters though!
> For example:
should be
> ).$3
>
function(inputValue: string, stateAndHelpers: object) | optional, no useful
> defaultCalled whenever the input value changes. Useful to use instead or in combination
of
onStateChange when inputValue is a controlled prop to
avoid issues with cursor positions.-
inputValue: The current value of the input
- stateAndHelpers: This is the same thing your children function is called
with (see Children Function)$3
>
number | optional, defaults the number of times you call getItemPropsThis is useful if you're using some kind of virtual listing component for
"windowing" (like
react-virtualized).$3
>
number | control prop (read more about this in
> the Control Props section)The index that should be highlighted
$3
>
string | control prop (read more about this in
> the Control Props section)The value the input should have
$3
>
boolean | control prop (read more about this in
> the Control Props section)Whether the menu should be considered open or closed. Some aspects of the
@xdanangelxoqenpm/harum-voluptates-eos component respond differently based on this value (for example, if
isOpen is true when the user hits "Enter" on the input field, then the item at
the highlightedIndex item is selected).$3
>
any/Array(any) | control prop (read more about this in
> the Control Props section)The currently selected item.
$3
>
string | defaults to a generated IDYou should not normally need to set this prop. It's only useful if you're server
rendering items (which each have an
id prop generated based on the @xdanangelxoqenpm/harum-voluptates-eos
id). For more information see the FAQ below.$3
>
string | defaults to a generated IDUsed for
aria attributes and the id prop of the element (input) you use
getInputProps with.$3
>
string | defaults to a generated IDUsed for
aria attributes and the id prop of the element (label) you use
getLabelProps with.$3
>
string | defaults to a generated IDUsed for
aria attributes and the id prop of the element (ul) you use
getMenuProps with.$3
>
function(index) | defaults to a function that generates an ID based on the
> indexUsed for
aria attributes and the id prop of the element (li) you use
getInputProps with.$3
>
window | defaults to windowThis prop is only useful if you're rendering @xdanangelxoqenpm/harum-voluptates-eos within a different
window context from where your JavaScript is running; for example, an iframe
or a shadow-root. If the given context is lacking document and/or
add|removeEventListener on its prototype (as is the case for a shadow-root)
then you will need to pass in a custom object that is able to provide
access to these properties
for @xdanangelxoqenpm/harum-voluptates-eos.$3
>
function(stateAndHelpers: object) | optionalA helper callback to help control internal state of @xdanangelxoqenpm/harum-voluptates-eos like
isOpen as
mentioned in this issue.
The same behavior can be achieved using onStateChange, but this prop is
provided as a helper because it's a fairly common use-case if you're controlling
the isOpen state:`jsx
const ui = (
isOpen={this.state.menuIsOpen}
onOuterClick={() => this.setState({menuIsOpen: false})}
>
{/ your callback /}
)
`This callback will only be called if
isOpen is true.$3
>
function(node: HTMLElement, menuNode: HTMLElement) | defaults to internal
> implementationThis allows you to customize how the scrolling works when the highlighted index
changes. It receives the node to be scrolled to and the root node (the root node
you render in @xdanangelxoqenpm/harum-voluptates-eos). Internally we use
compute-scroll-into-view
so if you use that package then you wont be adding any additional bytes to your
bundle :)stateChangeTypes
onStateChange and stateReducer). For you
to make the most of these APIs, it's important for you to understand why state
is being changed. To accomplish this, there's a type property on the changes
object you get. This type corresponds to a Downshift.stateChangeTypes
property.The list of all possible values this
type property can take is defined in
this file
and is as follows:-
Downshift.stateChangeTypes.unknown
- Downshift.stateChangeTypes.mouseUp
- Downshift.stateChangeTypes.itemMouseEnter
- Downshift.stateChangeTypes.keyDownArrowUp
- Downshift.stateChangeTypes.keyDownArrowDown
- Downshift.stateChangeTypes.keyDownEscape
- Downshift.stateChangeTypes.keyDownEnter
- Downshift.stateChangeTypes.keyDownHome
- Downshift.stateChangeTypes.keyDownEnd
- Downshift.stateChangeTypes.clickItem
- Downshift.stateChangeTypes.blurInput
- Downshift.stateChangeTypes.changeInput
- Downshift.stateChangeTypes.keyDownSpaceButton
- Downshift.stateChangeTypes.clickButton
- Downshift.stateChangeTypes.blurButton
- Downshift.stateChangeTypes.controlledPropUpdatedSelectedItem
- Downshift.stateChangeTypes.touchEndstateReducer for a concrete example on how to use the
type property.Control Props
@xdanangelxoqenpm/harum-voluptates-eos manages its own state internally and calls your
onChange and
onStateChange handlers with any relevant changes. The state that @xdanangelxoqenpm/harum-voluptates-eos
manages includes: isOpen, selectedItem, inputValue, and
highlightedIndex. Your Children function (read more below) can be used to
manipulate this state and can likely support many of your use cases.However, if more control is needed, you can pass any of these pieces of state as
a prop (as indicated above) and that state becomes controlled. As soon as
this.props[statePropKey] !== undefined, internally, @xdanangelxoqenpm/harum-voluptates-eos will determine
its state based on your prop's value rather than its own internal state. You
will be required to keep the state up to date (this is where onStateChange
comes in really handy), but you can also control the state from anywhere, be
that state from other components, redux, react-router, or anywhere else.> Note: This is very similar to how normal controlled components work elsewhere
> in react (like
). If you want to learn more about this concept, you
> can learn about that from this the
> Advanced React Component Patterns courseChildren Function
This is where you render whatever you want to based on the state of
@xdanangelxoqenpm/harum-voluptates-eos.
You use it like so:`javascript
const ui = (
{@xdanangelxoqenpm/harum-voluptates-eos => (
// use @xdanangelxoqenpm/harum-voluptates-eos utilities and state here, like @xdanangelxoqenpm/harum-voluptates-eos.isOpen,
// @xdanangelxoqenpm/harum-voluptates-eos.getInputProps, etc.
{/ more jsx here /}
)}
)
`The properties of this
@xdanangelxoqenpm/harum-voluptates-eos object can be split into three categories as
indicated below:$3
> See
> the blog post about prop getters
> NOTE: These prop-getters provide important
aria- attributes which are very
> important to your component being accessible. It's recommended that you
> utilize these functions and apply the props they give you to your components.These functions are used to apply props to the elements that you render. This
gives you maximum flexibility to render what, when, and wherever you like. You
call these on the element in question (for example:
)). It's advisable to pass all your props to that.| property | type | description |
| ---------------------- | ----------------- | ---------------------------------------------------------------------------------------------- |
|
getToggleButtonProps | function({}) | returns the props you should apply to any menu toggle button element you render. |
| getInputProps | function({}) | returns the props you should apply to the input element that you render. |
| getItemProps | function({}) | returns the props you should apply to any menu item elements you render. |
| getLabelProps | function({}) | returns the props you should apply to the label element that you render. |
| getMenuProps | function({},{}) | returns the props you should apply to the ul element (or root of your menu) that you render. |
| getRootProps | function({},{}) | returns the props you should apply to the root element that you render. It can be optional. |####
getRootProps
If you cannot render a div as the root element, then read this
Most of the time, you can just render a
div yourself and Downshift will
apply the props it needs to do its job (and you don't need to call this
function). However, if you're rendering a composite component (custom component)
as the root element, then you'll need to call getRootProps and apply that to
your root element (@xdanangelxoqenpm/harum-voluptates-eos will throw an error otherwise).There are no required properties for this method.
Optional properties:
-
refKey: if you're rendering a composite component, that component will need
to accept a prop which it forwards to the root DOM element. Commonly, folks
call this innerRef. So you'd call: getRootProps({refKey: 'innerRef'}) and
your composite component would forward like: .
It defaults to ref.If you're rendering a composite component,
Downshift checks that
getRootProps is called and that refKey is a prop of the returned composite
component. This is done to catch common causes of errors but, in some cases, the
check could fail even if the ref is correctly forwarded to the root DOM
component. In these cases, you can provide the object
{suppressRefError : true} as the second argument to getRootProps to
completely bypass the check.\
**Please use it with extreme care and only if you are absolutely sure that the ref
is correctly forwarded otherwise Downshift will unexpectedly fail.**\
See #235 for the
discussion that lead to this.####
getInputPropsThis method should be applied to the
input you render. It is recommended that
you pass all props as an object to this method which will compose together any
of the event handlers you need to apply to the input while preserving the ones
that @xdanangelxoqenpm/harum-voluptates-eos needs to apply to make the input behave.There are no required properties for this method.
Optional properties:
-
disabled: If this is set to true, then no event handlers will be returned
from getInputProps and a disabled prop will be returned (effectively
disabling the input).-
aria-label: By default the menu will add an aria-labelledby that refers to
the