downshift 🏎

The problem

You need an autocomplete/dropdown/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.

This solution

This is a component that controls user interactions and state for you so you can
create autocomplete/dropdown/select/etc. components. It uses 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.

selectedItemChanged

Used to determine if the new selectedItem has changed compared to the previous
selectedItem and properly update Downshift's internal state.

getA11yStatusMessage

function({/* see below */}) | default messages provided in English

This 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." or if there are results but no item is
highlighted, "resultCount results are available, use up and down arrow keys to
navigate." If an item is highlighted it will run itemToString(highlightedItem)
and display the value of the highlightedItem.

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

onSelect

Called when the user selects an item, regardless of the previous selected item.
Called with the item that was selected and the new state of downshift. (see
onStateChange for more info on stateAndHelpers).

selectedItem: The item that was just selected

stateAndHelpers: This is the same thing your render prop function is
called with (see Render Prop Function)

onStateChange

This function is called anytime the internal state changes. This can be useful
if you're using downshift 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 downshift 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 render prop function is
called with (see Render Prop 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').

stateReducer

function(state: object, changes: object) | optional

🚨 This is a really handy power feature 🚨

This function will be called each time downshift 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 downshift.

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.

onInputValueChange

Called 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 render prop function is
called with (see Render Prop Function)

itemCount

number | optional, defaults the number of times you call getItemProps

This is useful if you're using some kind of virtual listing component for
"windowing" (like
react-virtualized).

highlightedIndex

number | control prop (read more about this in the "Control Props"
section below)

The index that should be highlighted

inputValue

string | control prop (read more about this in the "Control Props"
section below)

The value the input should have

isOpen

boolean | control prop (read more about this in the "Control Props"
section below)

Whether the menu should be considered open or closed. Some aspects of the
downshift 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).

selectedItem

any/Array(any) | control prop (read more about this in the "Control
Props" section below)

The currently selected item.

render

function({}) | required

This is called with an object. Read more about the properties of this object in
the section "Render Prop Function".

id

string | defaults to a generated ID

You 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 downshiftid). For more information see the FAQ below.

environment

window | defaults to window

You should not normally need to set this prop. It's only useful if you're
rendering into a different window context from where your JavaScript is
running, for example an iframe.

onOuterClick

function | optional

A helper callback to help control internal state of downshift 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:

constui=(

<Downshift

isOpen={this.state.menuIsOpen}

onOuterClick={()=>this.setState({menuIsOpen:false})}

>

{/* your callback */}

</Downshift>

)

This callback will only be called if isOpen is true.

stateChangeTypes

There are a few props that expose changes to state
(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. If you want to see what change types
are available, run this in your app:

console.log(Object.keys(Downshift.stateChangeTypes))

Control Props

downshift manages its own state internally and calls your onChange and
onStateChange handlers with any relevant changes. The state that downshift
manages includes: isOpen, selectedItem, inputValue, and
highlightedIndex. Your render prop function (read more below) can be used to
manipulate this state from within the render function 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, downshift 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.

prop getters

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: <input {...getInputProps()})). It's advisable to pass all your props to that function
rather than applying them on the element yourself to avoid your props being
overridden (or overriding the props returned). For example:
getInputProps({onKeyUp(event) {console.log(event)}}).

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.

getRootProps

function({},{})

returns the props you should apply to the root element that you render. It can be optional.

getRootProps

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.

Required 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: <div ref={props.innerRef} />

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.

getInputProps

This 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 downshift 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).

getLabelProps

This method should be applied to the label you render. It is useful for
ensuring that the for attribute on the <label> (htmlFor as a react prop)
is the same as the id that appears on the input. If no htmlFor is provided
then an ID will be generated and used for the input and the labelfor
attribute.

There are no required properties for this method.

Note: You can definitely get by without using this (just provide an id to
your input and the same htmlFor to your label and you'll be good with
accessibility). However, we include this so you don't forget and it makes
things a little nicer for you. You're welcome 😀

getItemProps

The props returned from calling this function should be applied to any menu
items you render.

This is an impure function, so it should only be called when you will
actually be applying the props to an item.

What do you mean by impure function?

Basically just don't do this:

items.map(item=>{

constprops=getItemProps({item})// we're calling it here

if(!shouldRenderItem(item)){

returnnull// but we're not using props, and downshift thinks we are...

item: this is the item data that will be selected when the user selects a
particular item.

Optional properties:

index: This is how downshift keeps track of your item when updating the
highlightedIndex as the user keys around. By default, downshift will
assume the index is the order in which you're calling getItemProps. This
is often good enough, but if you find odd behavior, try setting this
explicitly. It's probably best to be explicit about index when using a
windowing library like react-virtualized.

disabled: If this is set to true, then all of the downshift item event
handlers will be omitted. Items will not be highlighted when hovered,
and items will not be selected when clicked.

getToggleButtonProps

Call this and apply the returned props to a button. It allows you to toggle
the Menu component. You can definitely build something like this yourself (all
of the available APIs are exposed to you), but this is nice because it will also
apply all of the proper ARIA attributes.

Optional properties:

disabled: If this is set to true, then all of the downshift button event
handlers will be omitted (it wont toggle the menu when clicked).

aria-label: The aria-label prop is in English. You should probably override
this yourself so you can provide translations:

constmyButton=(

<button

{...getToggleButtonProps({

'aria-label':translateWithId(isOpen ?'close.menu':'open.menu'),

})}

/>

)

actions

These are functions you can call to change the state of the downshift component.

property

type

description

clearSelection

function(cb: Function)

clears the selection

clearItems

function()

Clears downshift's record of all the items. Only really useful if you render your items asynchronously within downshift. See #186

closeMenu

function(cb: Function)

closes the menu

openMenu

function(cb: Function)

opens the menu

selectHighlightedItem

function(otherStateToSet: object, cb: Function)

selects the item that is currently highlighted

selectItem

function(item: any, otherStateToSet: object, cb: Function)

selects the given item

selectItemAtIndex

function(index: number, otherStateToSet: object, cb: Function)

selects the item at the given index

setHighlightedIndex

function(index: number, otherStateToSet: object, cb: Function)

call to set a new highlighted index

toggleMenu

function(otherStateToSet: object, cb: Function)

toggle the menu open state

reset

function(otherStateToSet: object, cb: Function)

this resets downshift's state to a reasonable default

setItemCount

function(count: number)

this sets the itemCount. Handy in situations where you're using windowing and the items are loaded asynchronously from within downshift (so you can't use the itemCount prop.

unsetItemCount

function()

this unsets the itemCount which means the item count will be calculated instead by the itemCount prop or based on how many times you call getItemProps.

setState

function(stateToSet: object, cb: Function)

This is a general setState function. It uses downshift's internalSetState function which works with control props and calls your onSelect, onChange, etc. (Note, you can specify a type which you can reference in some other APIs like the stateReducer).

otherStateToSet refers to an object to set other internal state. It is
recommended to avoid abusing this, but is available if you need it.

state

These are values that represent the current state of the downshift component.

property

type

description

highlightedIndex

number / null

the currently highlighted item

inputValue

string / null

the current value of the getInputProps input

isOpen

boolean

the menu open state

selectedItem

any

the currently selected item input

props

As a convenience, the id and itemToString props which you pass to
<Downshift /> are available here as well.

Event Handlers

Downshift has a few events for which it provides implicit handlers. Several of
these handlers call event.preventDefault(). Their additional functionality is
described below.

default handlers

ArrowDown: moves the highlighted index down by 1. If this shift key is held
when this event fires, the highlighted index will jump down 5 indices instead of 1.
NOTE: if the current highlighed index is within the bottom 5 indices, the top-most
index will be highlighted.)

ArrowUp: moves the highlighted index up by 1. If this shift key is held when
this event fires, the highlighted index will jump up 5 indices instead of 1. NOTE:
if the current highlighed index is within the top 5 indices, the bottom-most index
will be highlighted.)

Enter: if the menu is open, select the currently highlighted item. If the menu
is open, the usual 'Enter' event is prevented by Downshift's default implicit enter
handler; so, for example, a form submission event will not work as one might expect
(though if the menu is closed the form submission will work normally). See below
for customizing the handlers.

Escape: will reset downshift's state. This means that highlightedIndex will be
set to the defaultHighlightedIndex, the inputValue will be set to the itemToString
value of the selectedItem, and the isOpen state will be set to false.

customizing handlers

You can provide your own event handlers to Downshift which will be called before the default handlers:

constui=(

<Downshift>

{({getInputProps})=>(

<input

{...getInputProps({

onKeyDown:event=>{

// your handler code

},

})}

/>

)}

</Downshift>

)

If you would like to prevent the default handler behavior in some cases, you can set the event's preventDownshiftDefault property to true:

constui=(

<Downshift>

{({getInputProps})=>(

<input

{...getInputProps({

onKeyDown:event=>{

if(event.key==='Enter'){

// Prevent Downshift's default 'Enter' behavior.

event.preventDownshiftDefault=true

// your handler code

}

},

})}

/>

)}

</Downshift>

)

If you would like to completely override Downshift's behavior for a handler, in favor of your own, you can bypass prop getters:

constui=(

<Downshift>

{({getInputProps})=>(

<input

{...getInputProps()}

onKeyDown={event=>{

// your handler code

}}

/>

)}

</Downshift>

)

Utilities

resetIdCounter

Allows reseting the internal id counter which is used to generate unique ids for Downshift component.

You should never need to use this in the browser. Only if you are running an universal React app that is rendered on the server you should call resetIdCounter before every render so that the ids that get generated on the server match the ids generated in the browser.

FAQ

How do I avoid the checksum error when server rendering (SSR)?

The checksum error you're seeing is most likely due to the automatically
generated id and/or htmlFor prop you get from getInputProps and
getLabelProps (respectively). It could also be from the automatically
generated id prop you get from getItemProps (though this is not likely as
you're probably not rendering any items when rendering a downshift component on
the server).

To avoid these problems, simply call resetIdCounter before ReactDOM.renderToString.

Alternatively you could provide your own id prop in getInputProps
and getLabelProps. Also, you can use the id prop on the component
Downshift. For example:

constui=(

<Downshift

id="autocomplete"

render={({getInputProps, getLabelProps})=>(

<div>

<label {...getLabelProps({htmlFor:'autocomplete-input'})}>

Some Label

</label>

<input {...getInputProps({id:'autocomplete-input'})}/>

</div>

)}

/>

)

Upcoming Breaking Changes

We try to avoid breaking changes when possible and try to adhere to
semver. Sometimes breaking changes are necessary and we'll make the
transition as smooth as possible. This is why there's a prop available which
will allow you to opt into breaking changes. It looks like this:

constui=(

<Downshift

breakingChanges={

{

/* breaking change flags here */

}

}

render={()=><div />}

/>

)

To opt-into a breaking change, simply provide the key and value in the
breakingChanges object prop for each breaking change mentioned below:

resetInputOnSelection - Enable with the value of true. For more
information, see #243

When a new major version is released, then the code to support the old
functionality will be removed and the breaking change version will be the
default, so it's suggested you enable these as soon as you are aware of them.

Inspiration

I was heavily inspired by Ryan Florence. Watch his (free) lesson about
"Compound Components". Initially downshift was a
group of compound components using context to communicate. But then Jared
Forsyth suggested I expose functions (the prop getters) to get props to
apply to the elements rendered. That bit of inspiration made a big impact on the
flexibility and simplicity of this API.