- Notifications
You must be signed in to change notification settings - Fork946
🏎 A set of primitives to build simple, flexible, WAI-ARIA compliant React autocomplete, combobox or select dropdown components.
License
downshift-js/downshift
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Primitives to build simple, flexible, WAI-ARIA compliant Reactautocomplete, combobox or select dropdown components.
Read the docs |See the intro blog post|Listen to the Episode 79 of the Full Stack Radio podcast
You need an autocomplete, a combobox or a select experience in your applicationand you want it to be accessible. You also want it to be simple and flexible toaccount for your use cases. Finally, it should follow theARIA designpattern for acombobox or aselect, depending on your use case.
The library offers a couple of solutions. The first solution, which is the onewe recommend you to try first, is a set of React hooks. Each hook provides thestateful logic needed to make the corresponding component functional andaccessible. Navigate to the documentation for each by using the links in thelist below.
- useSelect for a custom select component.
- useCombobox for a combobox or autocomplete input.
- useMultipleSelection for selecting multiple itemsin a select or a combobox, as well as deleting items from selection ornavigating between the selected items.
The second solution is theDownshift component, which can also be used tocreate accessible combobox and select components, providing the logic in theform of a render prop. It served as inspiration for developing the hooks and ithas been around for a while. It established a successful pattern for makingcomponents accessible and functional while giving developers complete freedomwhen building the UI.
BothuseSelect anduseCombobox support the latest ARIA combobox patterns forW3C, whichDownshift does not. Consequently, we strongly recommend the you usethe hooks. The hooks have been migrated to the ARIA 1.2 combobox pattern in theversion 7 ofdownshift. There is aMigration Guide thatdocuments the changes introduced in version 7.
TheREADME on this page covers only the component while each hook has its ownREADME page. You can navigate to thehooks page or go directlyto 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 ourdocsite!
🚨 Use the Downshift hooks 🚨
If you are new to the library, consider theuseSelect anduseCombobox hooksas the first option. As mentioned above, the hooks benefit from the updated ARIApatterns and are actively maintained and improved. If there are use cases thatare supported by theDownshift component and not by the hooks, please createan issue in our repo. TheDownshift component is going to be removedcompletely once the hooks become mature.
This is a component that controls user interactions and state for you so you cancreate autocomplete, combobox or select dropdown components. It uses arenderprop which gives you maximum flexibility with a minimal APIbecause you are responsible for the rendering of everything and you simply applyprops to what you're rendering.
This differs from other solutions which render things for their use case andthen expose many options to allow for extensibility resulting in a bigger APIthat is less flexible as well as making the implementation more complicated andharder to contribute to.
NOTE: The original use case of this component is autocomplete, however the APIis powerful and flexible enough to build things like dropdowns as well.
- Installation
- Usage
- Basic Props
- 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
- Event Handlers
- Utilities
- React Native
- Advanced React Component Patterns course
- Examples
- FAQ
- Inspiration
- Other Solutions
- Bindings for ReasonML
- Contributors
- LICENSE
This module is distributed vianpm which is bundled withnode andshould be installed as one of your project'sdependencies:
npm install --save downshiftThis package also depends on
react. Please make sure you have it installedas well.
Note also this library supports
preactout of the box. If you are usingpreactthen use the corresponding module in thepreact/distfolder. Youcan evenimport Downshift from 'downshift/preact'👍
import*asReactfrom'react'import{render}from'react-dom'importDownshiftfrom'downshift'constitems=[{value:'apple'},{value:'pear'},{value:'orange'},{value:'grape'},{value:'banana'},]render(<DownshiftonChange={selection=>alert(selection ?`You selected${selection.value}` :'Selection Cleared')}itemToString={item=>(item ?item.value :'')}>{({ getInputProps, getItemProps, getLabelProps, getMenuProps, isOpen, inputValue, highlightedIndex, selectedItem, getRootProps,})=>(<div><label{...getLabelProps()}>Enter a fruit</label><divstyle={{display:'inline-block'}}{...getRootProps({},{suppressRefError:true})}><input{...getInputProps()}/></div><ul{...getMenuProps()}>{isOpen ?items.filter(item=>!inputValue||item.value.includes(inputValue)).map((item,index)=>(<li{...getItemProps({key:item.value, index, item,style:{backgroundColor:highlightedIndex===index ?'lightgray' :'white',fontWeight:selectedItem===item ?'bold' :'normal',},})}>{item.value}</li>)) :null}</ul></div>)}</Downshift>,document.getElementById('root'),)
There is also anexample without getRootProps.
Warning: The example without
getRootPropsis not fully accessible withscreen readers as it's not possible to achieve the HTML structure suggested byARIA. We recommend following the example withgetRootProps. Examples on howto useDownshiftcomponent with and withoutgetRootPropsare on thedocsite.
Downshift is the only component exposed by this package. It doesn't renderanything itself, it just calls the render function and renders that."Use arender prop!"!<Downshift>{downshift => <div>/* your JSX here! */</div>}</Downshift>.
This is the list of props that you should probably know about. There are someadvanced props below as well.
function({})|required
This is called with an object. Read more about the properties of this object inthe section "Children Function".
function(item: any)| defaults to:item => (item ? String(item) : '')
If your items are stored as, say, objects instead of strings, downshift stillneeds a string representation for each one (e.g., to setinputValue).
Note: This callbackmust include a null check: it is invoked withnullwhenever the user abandons input via<Esc>.
function(selectedItem: any, stateAndHelpers: object)| optional, no usefuldefault
Called when the selected item changes, either by the user selecting an item orthe user clearing the selection. Called with the item that was selected ornull and the new state ofdownshift. (seeonStateChange for more info onstateAndHelpers).
selectedItem: The item that was just selected.nullif the selection wascleared.stateAndHelpers: This is the same thing yourchildrenfunction is calledwith (seeChildren Function)
function(state: object, changes: object)| optional
🚨 This is a really handy power feature 🚨
This function will be called each timedownshift sets its internal state (orcalls youronStateChange handler for control props). It allows you to modifythe state change that will take place which can give you fine grain control overhow the component interacts with user updates without having to useControl Props. It gives you the current state and the statethat 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 atypeproperty which you can learn more about in thestateChangeTypessection.
constui=(<DownshiftstateReducer={stateReducer}>{/* your callback */}</Downshift>)functionstateReducer(state,changes){// this prevents the menu from being closed when the user// selects an item with a keyboard or mouseswitch(changes.type){caseDownshift.stateChangeTypes.keyDownEnter:caseDownshift.stateChangeTypes.clickItem:return{ ...changes,isOpen:state.isOpen,highlightedIndex:state.highlightedIndex,}default:returnchanges}}
NOTE: This is only called when state actually changes. You should not attemptto use this to handle events. If you wish to handle events, put your eventhandlers directly on the elements (make sure to use the prop getters though!For example:
<input onBlur={handleBlur} />should be<input {...getInputProps({onBlur: handleBlur})} />). Also, your reducerfunction should be "pure." This means it should do nothing other than returnthe state changes you want to have happen.
any| defaults tonull
Pass an item or an array of items that should be selected when downshift isinitialized.
string| defaults to''
This is the initial input value when downshift is initialized.
number/null| defaults todefaultHighlightedIndex
This is the initial value to set the highlighted index to when downshift isinitialized.
boolean| defaults todefaultIsOpen
This is the initialisOpen value when downshift is initialized.
number/null| defaults tonull
This is the value to set thehighlightedIndex to anytime downshift is reset,when the selection is cleared, when an item is selected or when the inputValueis changed.
boolean| defaults tofalse
This is the value to set theisOpen to anytime downshift is reset, when thethe selection is cleared, or when an item is selected.
function(prevItem: any, item: any)| defaults to:(prevItem, item) => (prevItem !== item)
Used to determine if the newselectedItem has changed compared to the previousselectedItem and properly update Downshift's internal state.
function({/* see below */})| default messages provided in English
This function is passed as props to aStatus component nested within andallows you to create your own assertive ARIA statuses.
A defaultgetA11yStatusMessage function is provided that will checkresultCount 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 followingproperties:
| 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 | TheisOpen state |
itemToString | function(any) | TheitemToString 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 |
function(selectedItem: any, stateAndHelpers: object)| optional, no usefuldefault
Called when the user selects an item, regardless of the previous selected item.Called with the item that was selected and the new state ofdownshift. (seeonStateChange for more info onstateAndHelpers).
selectedItem: The item that was just selectedstateAndHelpers: This is the same thing yourchildrenfunction is calledwith (seeChildren Function)
function(changes: object, stateAndHelpers: object)| optional, no usefuldefault
This function is called anytime the internal state changes. This can be usefulif you're using downshift as a "controlled" component, where you manage some orall of the state (e.g., isOpen, selectedItem, highlightedIndex, etc) and thenpass 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 laststate change. This also has atypeproperty which you can learn more aboutin thestateChangeTypessection.stateAndHelpers: This is the exact same thing yourchildrenfunction iscalled with (seeChildren Function)
Tip: This function will be called any timeany state is changed. The bestway 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 attemptto use this to handle events. If you wish to handle events, put your eventhandlers directly on the elements (make sure to use the prop getters though!For example:
<input onBlur={handleBlur} />should be<input {...getInputProps({onBlur: handleBlur})} />).
function(inputValue: string, stateAndHelpers: object)| optional, no usefuldefault
Called whenever the input value changes. Useful to use instead or in combinationofonStateChange wheninputValue is a controlled prop toavoid issues with cursor positions.
inputValue: The current value of the inputstateAndHelpers: This is the same thing yourchildrenfunction is calledwith (seeChildren Function)
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" (likereact-virtualized).
number|control prop (read more about this inthe Control Props section)
The index that should be highlighted
string|control prop (read more about this inthe Control Props section)
The value the input should have
boolean|control prop (read more about this inthe Control Props section)
Whether the menu should be considered open or closed. Some aspects of thedownshift component respond differently based on this value (for example, ifisOpen is true when the user hits "Enter" on the input field, then the item atthehighlightedIndex item is selected).
any/Array(any)|control prop (read more about this inthe Control Props section)
The currently selected item.
string| defaults to a generated ID
You should not normally need to set this prop. It's only useful if you're serverrendering items (which each have anid prop generated based on thedownshiftid). For more information see theFAQ below.
string| defaults to a generated ID
Used foraria attributes and theid prop of the element (input) you usegetInputProps with.
string| defaults to a generated ID
Used foraria attributes and theid prop of the element (label) you usegetLabelProps with.
string| defaults to a generated ID
Used foraria attributes and theid prop of the element (ul) you usegetMenuProps with.
function(index)| defaults to a function that generates an ID based on theindex
Used foraria attributes and theid prop of the element (li) you usegetInputProps with.
window| defaults towindow
This prop is only useful if you're rendering downshift within a differentwindow context from where your JavaScript is running; for example, an iframeor a shadow-root. If the given context is lackingdocument and/oradd|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 provideaccess to these propertiesfor downshift.
function(stateAndHelpers: object)| optional
A helper callback to help control internal state of downshift likeisOpen asmentioned inthis issue.The same behavior can be achieved usingonStateChange, but this prop isprovided as a helper because it's a fairly common use-case if you're controllingtheisOpen state:
constui=(<DownshiftisOpen={this.state.menuIsOpen}onOuterClick={()=>this.setState({menuIsOpen:false})}>{/* your callback */}</Downshift>)
This callback will only be called ifisOpen istrue.
function(node: HTMLElement, menuNode: HTMLElement)| defaults to internalimplementation
This allows you to customize how the scrolling works when the highlighted indexchanges. It receives the node to be scrolled to and the root node (the root nodeyou render in downshift). Internally we usecompute-scroll-into-viewso if you use that package then you wont be adding any additional bytes to yourbundle :)
There are a few props that expose changes to state(onStateChange andstateReducer). For youto make the most of these APIs, it's important for you to understand why stateis being changed. To accomplish this, there's atype property on thechangesobject you get. Thistype corresponds to aDownshift.stateChangeTypesproperty.
The list of all possible values thistype property can take is defined inthis fileand is as follows:
Downshift.stateChangeTypes.unknownDownshift.stateChangeTypes.mouseUpDownshift.stateChangeTypes.itemMouseEnterDownshift.stateChangeTypes.keyDownArrowUpDownshift.stateChangeTypes.keyDownArrowDownDownshift.stateChangeTypes.keyDownEscapeDownshift.stateChangeTypes.keyDownEnterDownshift.stateChangeTypes.keyDownHomeDownshift.stateChangeTypes.keyDownEndDownshift.stateChangeTypes.clickItemDownshift.stateChangeTypes.blurInputDownshift.stateChangeTypes.changeInputDownshift.stateChangeTypes.keyDownSpaceButtonDownshift.stateChangeTypes.clickButtonDownshift.stateChangeTypes.blurButtonDownshift.stateChangeTypes.controlledPropUpdatedSelectedItemDownshift.stateChangeTypes.touchEnd
SeestateReducer for a concrete example on how to use thetype property.
downshift manages its own state internally and calls youronChange andonStateChange handlers with any relevant changes. The state that downshiftmanages includes:isOpen,selectedItem,inputValue, andhighlightedIndex. Your Children function (read more below) can be used tomanipulate 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 asa prop (as indicated above) and that state becomes controlled. As soon asthis.props[statePropKey] !== undefined, internally,downshift will determineits state based on your prop's value rather than its own internal state. Youwill be required to keep the state up to date (this is whereonStateChangecomes in really handy), but you can also control the state from anywhere, bethat state from other components,redux,react-router, or anywhere else.
Note: This is very similar to how normal controlled components work elsewherein react (like
<input />). If you want to learn more about this concept, youcan learn about that from this theAdvanced React Component Patterns course
This is where you render whatever you want to based on the state ofdownshift.You use it like so:
constui=(<Downshift>{downshift=>(// use downshift utilities and state here, like downshift.isOpen,// downshift.getInputProps, etc.<div>{/* more jsx here */}</div>)}</Downshift>)
The properties of thisdownshift object can be split into three categories asindicated below:
NOTE: These prop-getters provide important
aria-attributes which are veryimportant to your component being accessible. It's recommended that youutilize 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. Thisgives you maximum flexibility to render what, when, and wherever you like. Youcall these on the element in question (for example:<input {...getInputProps()})). It's advisable to pass all your props to thatfunction rather than applying them on the element yourself to avoid your propsbeing 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 theinput 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 thelabel element that you render. |
getMenuProps | function({},{}) | returns the props you should apply to theul 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. |
If you cannot render a div as the root element, then read this
Most of the time, you can just render adiv yourself andDownshift willapply the props it needs to do its job (and you don't need to call thisfunction). However, if you're rendering a composite component (custom component)as the root element, then you'll need to callgetRootProps and apply that toyour root element (downshift 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 needto accept a prop which it forwards to the root DOM element. Commonly, folkscall thisinnerRef. So you'd call:getRootProps({refKey: 'innerRef'})andyour composite component would forward like:<div ref={props.innerRef} />.It defaults toref.
If you're rendering a composite component,Downshift checks thatgetRootProps is called and thatrefKey is a prop of the returned compositecomponent. This is done to catch common causes of errors but, in some cases, thecheck could fail even if the ref is correctly forwarded to the root DOMcomponent. In these cases, you can provide the object{suppressRefError : true} as the second argument togetRootProps tocompletely bypass the check.
Please use it with extreme care and only if you are absolutely sure that the refis correctly forwarded otherwiseDownshift will unexpectedly fail.
See#235 for thediscussion that lead to this.
This method should be applied to theinput you render. It is recommended thatyou pass all props as an object to this method which will compose together anyof the event handlers you need to apply to theinput while preserving the onesthatdownshift needs to apply to make theinput behave.
There are no required properties for this method.
Optional properties:
disabled: If this is set to true, then no event handlers will be returnedfromgetInputPropsand adisabledprop will be returned (effectivelydisabling the input).aria-label: By default the menu will add anaria-labelledbythat refers tothe<label>rendered withgetLabelProps. However, if you providearia-labelto give a more specific label that describes the optionsavailable, thenaria-labelledbywill not be provided and screen readers canuse youraria-labelinstead.
This method should be applied to thelabel you render. It is useful forensuring that thefor attribute on the<label> (htmlFor as a react prop)is the same as theid that appears on theinput. If nohtmlFor is provided(the normal case) then an ID will be generated and used for theinput and thelabelfor attribute.
There are no required properties for this method.
Note: For accessibility purposes, calling this method is highly recommended.
This method should be applied to the element which contains your list of items.Typically, this will be a<div> or a<ul> that surrounds amap expression.This handles the proper ARIA roles and attributes.
Optional properties:
refKey: if you're rendering a composite component, that component will needto accept a prop which it forwards to the root DOM element. Commonly, folkscall thisinnerRef. So you'd call:getMenuProps({refKey: 'innerRef'})andyour composite component would forward like:<ul ref={props.innerRef} />.However, if you are just rendering a primitive component like<div>, thereis no need to specify this property. It defaults toref.Please keep in mind that menus, for accessibility purposes, should always berendered, regardless of whether you hide it or not. Otherwise,
getMenuPropsmay throw error if you unmount and remount the menu.aria-label: By default the menu will add anaria-labelledbythat refers tothe<label>rendered withgetLabelProps. However, if you providearia-labelto give a more specific label that describes the optionsavailable, thenaria-labelledbywill not be provided and screen readers canuse youraria-labelinstead.
In some cases, you might want to completely bypass therefKey check. Then youcan provide the object{suppressRefError : true} as the second argument togetMenuProps.Please use it with extreme care and only if you are absolutelysure that the ref is correctly forwarded otherwiseDownshift will unexpectedlyfail.
<ul{...getMenuProps()}>{!isOpen ?null :items.map((item,index)=>(<li{...getItemProps({item, index,key:item.id})}>{item.name}</li>))}</ul>
Note that for accessibility reasons it's best if you always render thiselement whether or not downshift is in an
isOpenstate.
The props returned from calling this function should be applied to any menuitems you render.
This is an impure function, so it should only be called when you willactually 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 hereif(!shouldRenderItem(item)){returnnull// but we're not using props, and downshift thinks we are...}return<div{...props}/>})
Instead, you could do this:
items.filter(shouldRenderItem).map(item=><div{...getItemProps({item})}/>)
Required properties:
item: this is the item data that will be selected when the user selects aparticular item.
Optional properties:
index: This is howdownshiftkeeps track of your item when updating thehighlightedIndexas the user keys around. By default,downshiftwillassume theindexis the order in which you're callinggetItemProps. Thisis often good enough, but if you find odd behavior, try setting thisexplicitly. It's probably best to be explicit aboutindexwhen using awindowing library likereact-virtualized.disabled: If this is set totrue, then all of the downshift item eventhandlers will be omitted. Items will not be highlighted when hovered, anditems will not be selected when clicked.
Call this and apply the returned props to abutton. It allows you to toggletheMenu component. You can definitely build something like this yourself (allof the available APIs are exposed to you), but this is nice because it will alsoapply all of the proper ARIA attributes.
Optional properties:
disabled: If this is set totrue, then all of the downshift button eventhandlers will be omitted (it wont toggle the menu when clicked).aria-label: Thearia-labelprop is in English. You should probablyoverride this yourself so you can provide translations:
constmyButton=(<button{...getToggleButtonProps({'aria-label':translateWithId(isOpen ?'close.menu' :'open.menu'),})}/>)
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 theitemCount. Handy in situations where you're using windowing and the items are loaded asynchronously from within downshift (so you can't use theitemCount prop. |
unsetItemCount | function() | this unsets theitemCount which means the item count will be calculated instead by theitemCount prop or based on how many times you callgetItemProps. |
setState | function(stateToSet: object, cb: Function) | This is a generalsetState function. It uses downshift'sinternalSetState function which works with control props and calls youronSelect,onChange, etc. (Note, you can specify atype which you can reference in some other APIs like thestateReducer). |
otherStateToSetrefers to an object to set other internal state. It isrecommended to avoid abusing this, but is available if you need it.
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 thegetInputProps input |
isOpen | boolean | the menu open state |
selectedItem | any | the currently selected item input |
As a convenience, theid anditemToString props which you pass to<Downshift /> are available here as well.
Downshift has a few events for which it provides implicit handlers. Several ofthese handlers callevent.preventDefault(). Their additional functionality isdescribed below.
ArrowDown: if menu is closed, opens it and moves the highlighted index todefaultHighlightedIndex + 1, ifdefaultHighlightedIndexis provided, or tothe top-most item, if not. If menu is open, it moves the highlighted indexdown by 1. If the shift key is held when this event fires, the highlightedindex will jump down 5 indices instead of 1. NOTE: if the current highlightedindex is within the bottom 5 indices, the top-most index will be highlighted.)ArrowUp: if menu is closed, opens it and moves the highlighted index todefaultHighlightedIndex - 1, ifdefaultHighlightedIndexis provided, or tothe bottom-most item, if not. If menu is open, moves the highlighted index upby 1. If the shift key is held when this event fires, the highlighted indexwill jump up 5 indices instead of 1. NOTE: if the current highlighted index iswithin the top 5 indices, the bottom-most index will be highlighted.)Home: if menu is closed, it will not add any other behavior. If menu isopen, the top-most index will get highlighted.End: if menu is closed, it will not add any other behavior. If menu is open,the bottom-most index will get highlighted.Enter: if the menu is open, selects the currently highlighted item. If themenu is open, the usual 'Enter' event is prevented by Downshift's defaultimplicit enter handler; so, for example, a form submission event will not workas one might expect (though if the menu is closed the form submission willwork normally). See below for customizing the handlers.Escape: will clear downshift's state. This means thathighlightedIndexwill be set to thedefaultHighlightedIndexand theisOpenstate will beset to thedefaultIsOpen. IfisOpenis already false, theinputValuewill be set to an empty string andselectedItemwill be set tonull
You can provide your own event handlers to Downshift which will be called beforethe 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 canset the event'spreventDownshiftDefault property totrue:
constui=(<Downshift>{({getInputProps})=>(<input{...getInputProps({onKeyDown:event=>{if(event.key==='Enter'){// Prevent Downshift's default 'Enter' behavior.event.nativeEvent.preventDownshiftDefault=true// your handler code}},})}/>)}</Downshift>)
If you would like to completely override Downshift's behavior for a handler, infavor of your own, you can bypass prop getters:
constui=(<Downshift>{({getInputProps})=>(<input{...getInputProps()}onKeyDown={event=>{// your handler code}}/>)}</Downshift>)
Allows reseting the internal id counter which is used to generate unique ids forDownshift component.
This is unnecessary if you are using React 18 or newer
You should never need to use this in the browser. Only if you are running anuniversal React app that is rendered on the server you should callresetIdCounter before every render so that the ids that getgenerated on the server match the ids generated in the browser.
import{resetIdCounter}from'downshift';resetIdCounter()ReactDOMServer.renderToString(...);
Since Downshift renders it's UI using render props, Downshift supports renderingon React Native with ease. Use components like<View>,<Text>,<TouchableOpacity> and others inside of your render method to generate awesomeautocomplete, dropdown, or selection components.
- Your root view will need to either pass a ref to
getRootPropsor callgetRootPropswith{ suppressRefError: true }. This ref is used to catch acommon set of errors around composite components.Learn more ingetRootProps. - When using a
<FlatList>or<ScrollView>, be sure to supply thekeyboardShouldPersistTapsprop to ensure that your text input stays focus, while allowing for taps onthe touchables rendered for your items.
Kent C. Dodds has created learning materialbased on the patterns implemented in this component. You can find it on variousplatforms:
- egghead.io
- Frontend Masters
- YouTube (for free!):Part 1andPart 2
🚨 We're in the process of moving all examples to thedownshift-examples repo(which you can open, interact with, and contribute back to live oncodesandbox)
🚨 We're also in the process of updating our examples from thedownshift-docs repo which isactually used to create our docsite atdownshift-js.com). Make sureto check it out for the most relevant Downshift examples or try out the newhooks that aim to replace Downshift.
Ordered Examples:
If you're just learning downshift, review these in order:
- basic automplete with getRootProps -the same as example #1 but using the correct HTML structure as suggested byARIA-WCAG.
- basic autocomplete -very bare bones, not styled at all. Good place to start.
- styled autocomplete -more complete autocomplete solution using emotion for styling andmatch-sorter for filtering the items.
- typeahead -Shows how to control the
selectedItemso the selected item can be one ofyour items or whatever the user types. - multi-select -Shows how to create a MultiDownshift component that allows for an array ofselectedItems for multiple selection using a state reducer
Other Examples:
Check out these examples of more advanced use/edge cases:
- dropdown with select by key -An example of using the render prop pattern to utilize a reusable component toprovide the downshift dropdown component with the functionality of being ableto highlight a selection item that starts with the key pressed.
- using actions -An example of using one of downshift's actions as an event handler.
- gmail's composition recipients field -An example of a highly complex autocomplete component featuring asynchronouslyloading items, multiple selection, and windowing (with react-virtualized)
- Downshift HOC and Compound Components -An example of how to implementat compound components with
React.createContextand a downshift higher order component. This isgenerally not recommended because the render prop API exported by downshift isgenerally good enough for everyone, but there's nothing technically wrong withdoing something like this.
Old Examples exist oncodesandbox.io:
🚨 This is a great contribution opportunity! These are examples that have notyet been migrated todownshift-examples.You're more than welcome to make PRs to the examples repository to move theseexamples over there.Watch this to learn how to contribute completely in the browser
- Integration with Apollo
- Integration with Redux
- Integration with
react-instantsearchfrom Algolia - Material-UI (1.0.0-beta.4) Combobox Using Downshift
- Material-UI (1.0.0-beta.33) Multiple select with autocomplete
- Integration with
GenieJS(learn more aboutgeniehere) - Handling and displaying errors
- Integration with React Router
- Windowing with
react-tiny-virtual-list - Section/option group example
- Integration with
fuzzaldrin-plus(Fuzzy matching) - Dropdown/select implementation with Bootstrap
- Multiple editable tag selection
- Downshift implemented as compound components and a Higher Order Component(exposes a
withDownshifthigher order component which you can use to get atthe state, actions, prop getters in a rendered downshift tree). - Downshift Spectre.css example
- Integration with
redux-form - Integration with
react-final-form - Provider Pattern - how to avoidprop-drilling if you like to break up your render method into more components
- React Native example
- React VR example
- Multiple checkbox selection
How do I avoid the checksum error when server rendering (SSR)?
The checksum error you're seeing is most likely due to the automaticallygeneratedid and/orhtmlFor prop you get fromgetInputProps andgetLabelProps (respectively). It could also be from the automaticallygeneratedid prop you get fromgetItemProps (though this is not likely asyou're probably not rendering any items when rendering a downshift component onthe server).
To avoid these problems, simply callresetIdCounter beforeReactDOM.renderToString.
Alternatively you could provide your own ids via the id props where you render<Downshift />:
constui=(<Downshiftid="autocomplete"labelId="autocomplete-label"inputId="autocomplete-input"menuId="autocomplete-menu">{({getInputProps, getLabelProps})=><div>{/* your UI */}</div>}</Downshift>)
I was heavily inspired byRyan Florence. Watch his (free) lesson about"Compound Components". Initially downshift was agroup of compound components using context to communicate. But thenJaredForsyth suggested I expose functions (the prop getters) to get props toapply to the elements rendered. That bit of inspiration made a big impact on theflexibility and simplicity of this API.
I also took a few ideas from the code inreact-autocomplete andjQuery UI'sAutocomplete.
You can watch me build the first iteration ofdownshift on YouTube:
You'll find more recordings of me working ondownshift onmy livestreamYouTube playlist.
You can implement these other solutions usingdownshift, but if you'd preferto use these out of the box solutions, then that's fine too:
If you're developing some React in ReasonML, check out theDownshift bindings forthat.
Thanks goes to these people (emoji key):
This project follows theall-contributors specification.Contributions of any kind welcome!
MIT
About
🏎 A set of primitives to build simple, flexible, WAI-ARIA compliant React autocomplete, combobox or select dropdown components.
Topics
Resources
License
Code of conduct
Contributing
Uh oh!
There was an error while loading.Please reload this page.