Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🏎 A set of primitives to build simple, flexible, WAI-ARIA compliant React autocomplete, combobox or select dropdown components.

License

NotificationsYou must be signed in to change notification settings

downshift-js/downshift

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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


Build StatusCode CoveragedownloadsversionMIT License

All ContributorsPRs WelcomeChatCode of ConductJoin the community on Spectrum

Supports React and Preactsizegzip sizemodule formats: umd, cjs, and es

The problem

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.

This solution

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.

Downshift

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.

Table of Contents

Installation

This module is distributed vianpm which is bundled withnode andshould be installed as one of your project'sdependencies:

npm install --save downshift

This package also depends onreact. Please make sure you have it installedas well.

Note also this library supportspreact out of the box. If you are usingpreact then use the corresponding module in thepreact/dist folder. Youcan evenimport Downshift from 'downshift/preact' 👍

Usage

Try it out in the browser

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 withoutgetRootProps is 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 useDownshift component with and withoutgetRootProps are 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>.

Basic Props

This is the list of props that you should probably know about. There are someadvanced props below as well.

children

function({}) |required

This is called with an object. Read more about the properties of this object inthe section "Children Function".

itemToString

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>.

onChange

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.null if the selection wascleared.
  • stateAndHelpers: This is the same thing yourchildren function is calledwith (seeChildren Function)

stateReducer

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 atype property which you can learn more about in thestateChangeTypes section.
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.

Advanced Props

initialSelectedItem

any | defaults tonull

Pass an item or an array of items that should be selected when downshift isinitialized.

initialInputValue

string | defaults to''

This is the initial input value when downshift is initialized.

initialHighlightedIndex

number/null | defaults todefaultHighlightedIndex

This is the initial value to set the highlighted index to when downshift isinitialized.

initialIsOpen

boolean | defaults todefaultIsOpen

This is the initialisOpen value when downshift is initialized.

defaultHighlightedIndex

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.

defaultIsOpen

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.

selectedItemChanged

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.

getA11yStatusMessage

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:

propertytypedescription
highlightedIndexnumber/nullThe currently highlighted index
highlightedItemanyThe value of the highlighted item
inputValuestringThe current input value
isOpenbooleanTheisOpen state
itemToStringfunction(any)TheitemToString function (see props) for getting the string value from one of the options
previousResultCountnumberThe total items showing in the dropdown the last time the status was updated
resultCountnumberThe total items showing in the dropdown
selectedItemanyThe value of the currently selected item

onSelect

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 selected
  • stateAndHelpers: This is the same thing yourchildren function is calledwith (seeChildren Function)

onStateChange

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 atype property which you can learn more aboutin thestateChangeTypes section.
  • stateAndHelpers: This is the exact same thing yourchildren function 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 usechanges.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})} />).

onInputValueChange

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 input
  • stateAndHelpers: This is the same thing yourchildren function is calledwith (seeChildren 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" (likereact-virtualized).

highlightedIndex

number |control prop (read more about this inthe Control Props section)

The index that should be highlighted

inputValue

string |control prop (read more about this inthe Control Props section)

The value the input should have

isOpen

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

selectedItem

any/Array(any) |control prop (read more about this inthe Control Props section)

The currently selected item.

id

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.

inputId

string | defaults to a generated ID

Used foraria attributes and theid prop of the element (input) you usegetInputProps with.

labelId

string | defaults to a generated ID

Used foraria attributes and theid prop of the element (label) you usegetLabelProps with.

menuId

string | defaults to a generated ID

Used foraria attributes and theid prop of the element (ul) you usegetMenuProps with.

getItemId

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.

environment

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.

onOuterClick

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.

scrollIntoView

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 :)

stateChangeTypes

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.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.touchEnd

SeestateReducer for a concrete example on how to use thetype property.

Control Props

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

Children Function

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:

prop getters

Seethe blog post about prop getters

NOTE: These prop-getters provide importantaria- 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)}}).

propertytypedescription
getToggleButtonPropsfunction({})returns the props you should apply to any menu toggle button element you render.
getInputPropsfunction({})returns the props you should apply to theinput element that you render.
getItemPropsfunction({})returns the props you should apply to any menu item elements you render.
getLabelPropsfunction({})returns the props you should apply to thelabel element that you render.
getMenuPropsfunction({},{})returns the props you should apply to theul element (or root of your menu) that you render.
getRootPropsfunction({},{})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 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.

getInputProps

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 returnedfromgetInputProps and adisabled prop will be returned (effectivelydisabling the input).

  • aria-label: By default the menu will add anaria-labelledby that refers tothe<label> rendered withgetLabelProps. However, if you providearia-label to give a more specific label that describes the optionsavailable, thenaria-labelledby will not be provided and screen readers canuse youraria-label instead.

getLabelProps

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.

getMenuProps

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-labelledby that refers tothe<label> rendered withgetLabelProps. However, if you providearia-label to give a more specific label that describes the optionsavailable, thenaria-labelledby will not be provided and screen readers canuse youraria-label instead.

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 anisOpen state.

getItemProps

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 howdownshift keeps track of your item when updating thehighlightedIndex as the user keys around. By default,downshift willassume theindex is 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 aboutindex when 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.

getToggleButtonProps

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-label prop is in English. You should probablyoverride 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.

propertytypedescription
clearSelectionfunction(cb: Function)clears the selection
clearItemsfunction()Clears downshift's record of all the items. Only really useful if you render your items asynchronously within downshift. See#186
closeMenufunction(cb: Function)closes the menu
openMenufunction(cb: Function)opens the menu
selectHighlightedItemfunction(otherStateToSet: object, cb: Function)selects the item that is currently highlighted
selectItemfunction(item: any, otherStateToSet: object, cb: Function)selects the given item
selectItemAtIndexfunction(index: number, otherStateToSet: object, cb: Function)selects the item at the given index
setHighlightedIndexfunction(index: number, otherStateToSet: object, cb: Function)call to set a new highlighted index
toggleMenufunction(otherStateToSet: object, cb: Function)toggle the menu open state
resetfunction(otherStateToSet: object, cb: Function)this resets downshift's state to a reasonable default
setItemCountfunction(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.
unsetItemCountfunction()this unsets theitemCount which means the item count will be calculated instead by theitemCount prop or based on how many times you callgetItemProps.
setStatefunction(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).

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

state

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

propertytypedescription
highlightedIndexnumber /nullthe currently highlighted item
inputValuestring /nullthe current value of thegetInputProps input
isOpenbooleanthe menu open state
selectedItemanythe currently selected item input

props

As a convenience, theid anditemToString 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 ofthese handlers callevent.preventDefault(). Their additional functionality isdescribed below.

default handlers

  • ArrowDown: if menu is closed, opens it and moves the highlighted index todefaultHighlightedIndex + 1, ifdefaultHighlightedIndex is 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, ifdefaultHighlightedIndex is 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 thedefaultHighlightedIndex and theisOpen state will beset to thedefaultIsOpen. IfisOpen is already false, theinputValuewill be set to an empty string andselectedItem will be set tonull

customizing handlers

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>)

Utilities

resetIdCounter

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(...);

React Native

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.

Gotchas

  • Your root view will need to either pass a ref togetRootProps or callgetRootProps with{ 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.

Advanced React Component Patterns course

Kent C. Dodds has created learning materialbased on the patterns implemented in this component. You can find it on variousplatforms:

  1. egghead.io
  2. Frontend Masters
  3. YouTube (for free!):Part 1andPart 2

Examples

🚨 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:

  1. basic automplete with getRootProps -the same as example #1 but using the correct HTML structure as suggested byARIA-WCAG.
  2. basic autocomplete -very bare bones, not styled at all. Good place to start.
  3. styled autocomplete -more complete autocomplete solution using emotion for styling andmatch-sorter for filtering the items.
  4. typeahead -Shows how to control theselectedItem so the selected item can be one ofyour items or whatever the user types.
  5. 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 withReact.createContext and 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

FAQ

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>)

Inspiration

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.

Other Solutions

You can implement these other solutions usingdownshift, but if you'd preferto use these out of the box solutions, then that's fine too:

Bindings for ReasonML

If you're developing some React in ReasonML, check out theDownshift bindings forthat.

Contributors

Thanks goes to these people (emoji key):

Kent C. Dodds
Kent C. Dodds

💻📖🚇⚠️👀📝🐛💡🤔📢
Ryan Florence
Ryan Florence

🤔
Jared Forsyth
Jared Forsyth

🤔📖
Jack Moore
Jack Moore

💡
Travis Arnold
Travis Arnold

💻📖
Marcy Sutton
Marcy Sutton

🐛🤔
Jeremy Gayed
Jeremy Gayed

💡
Haroen Viaene
Haroen Viaene

💡
monssef
monssef

💡
Federico Zivolo
Federico Zivolo

📖
Divyendu Singh
Divyendu Singh

💡💻📖⚠️
Muhammad Salman
Muhammad Salman

💻
João Alberto
João Alberto

💻
Bernard Lin
Bernard Lin

💻📖
Geoff Davis
Geoff Davis

💡
Anup
Anup

📖
Ferdinand Salis
Ferdinand Salis

🐛💻
Kye Hohenberger
Kye Hohenberger

🐛
Julien Goux
Julien Goux

🐛💻⚠️
Joachim Seminck
Joachim Seminck

💻
Jesse Harlin
Jesse Harlin

🐛💡
Matt Parrish
Matt Parrish

🔧👀
thom
thom

💻
Vu Tran
Vu Tran

💻
Codie Mullins
Codie Mullins

💻💡
Mohammad Rajabifard
Mohammad Rajabifard

📖🤔
Frank Tan
Frank Tan

💻
Kier Borromeo
Kier Borromeo

💡
Paul Veevers
Paul Veevers

💻
Ron Cruz
Ron Cruz

📖
Rick McGavin
Rick McGavin

📖
Jelle Versele
Jelle Versele

💡
Brent Ertz
Brent Ertz

🤔
Justice Mba
Justice Mba

💻📖🤔
Mark Ellis
Mark Ellis

🤔
us͡an̸df͘rien͜ds͠
us͡an̸df͘rien͜ds͠

🐛💻⚠️
Robin Drexler
Robin Drexler

🐛💻
Arturo Romero
Arturo Romero

💡
yp
yp

🐛💻⚠️
Dave Garwacke
Dave Garwacke

📖
Ivan Pazhitnykh
Ivan Pazhitnykh

💻⚠️
Luis Merino
Luis Merino

📖
Andrew Hansen
Andrew Hansen

💻⚠️🤔
John Whiles
John Whiles

💻
Justin Hall
Justin Hall

🚇
Pete Nykänen
Pete Nykänen

👀
Jared Palmer
Jared Palmer

💻
Philip Young
Philip Young

💻⚠️🤔
Alexander Nanberg
Alexander Nanberg

📖💻
Pete Redmond
Pete Redmond

🐛
Nick Lavin
Nick Lavin

🐛💻⚠️
James Long
James Long

🐛💻
Michael Ball
Michael Ball

🐛💻⚠️
CAVALEIRO Julien
CAVALEIRO Julien

💡
Kim Grönqvist
Kim Grönqvist

💻⚠️
Sijie
Sijie

🐛💻
Dony Sukardi
Dony Sukardi

💡💬💻⚠️
Dillon Mulroy
Dillon Mulroy

📖
Curtis Tate Wilkinson
Curtis Tate Wilkinson

💻
Brice BERNARD
Brice BERNARD

🐛💻
Tony Xu
Tony Xu

💻
Anthony Ng
Anthony Ng

📖
S S
S S

💬💻📖🤔⚠️
Austin Tackaberry
Austin Tackaberry

💬💻📖🐛💡🤔👀⚠️
Jean Duthon
Jean Duthon

🐛💻
Anton Telesh
Anton Telesh

🐛💻
Eric Edem
Eric Edem

💻📖🤔⚠️
Austin Wood
Austin Wood

💬📖👀
Mark Murray
Mark Murray

🚇
Gianmarco
Gianmarco

🐛💻
Emmanuel Pastor
Emmanuel Pastor

💡
dalehurwitz
dalehurwitz

💻
Bogdan Lobor
Bogdan Lobor

🐛💻
Luke Herrington
Luke Herrington

💡
Brandon Clemons
Brandon Clemons

💻
Kieran
Kieran

💻
Brushedoctopus
Brushedoctopus

🐛💻
Cameron Edwards
Cameron Edwards

💻⚠️
stereobooster
stereobooster

💻⚠️
Trevor Pierce
Trevor Pierce

👀
Xuefei Li
Xuefei Li

💻
Alfred Ringstad
Alfred Ringstad

💻
D[oa]vid Weisz
D[oa]vid Weisz

💻
Royston Shufflebotham
Royston Shufflebotham

🐛💻
Michaël De Boey
Michaël De Boey

💻
Henry
Henry

💻
Andrew Walton
Andrew Walton

🐛💻⚠️
Arthur Denner
Arthur Denner

💻
Cody Olsen
Cody Olsen

💻
Thomas Ladd
Thomas Ladd

💻
lixualinta
lixualinta

💻
Jacob Cofman
Jacob Cofman

💻
Joshua Freedman
Joshua Freedman

💻
Amy
Amy

💡
Rogin Farrer
Rogin Farrer

💻
Dmitrii Kanatnikov
Dmitrii Kanatnikov

💻
Dallon Feldner
Dallon Feldner

🐛💻
Samuel Fuller Thomas
Samuel Fuller Thomas

💻
Ryan Castner
Ryan Castner

💻
Silviu Alexandru Avram
Silviu Alexandru Avram

🐛💻⚠️
Anton Volkov
Anton Volkov

💻⚠️
Keegan Street
Keegan Street

🐛💻
Manuel Dugué
Manuel Dugué

💻
Max Karadeniz
Max Karadeniz

💻
Gonzalo Beviglia
Gonzalo Beviglia

🐛💻👀
Brian Kilrain
Brian Kilrain

🐛💻⚠️📖
Gerd Zschaler
Gerd Zschaler

💻🐛
Karen Gasparyan
Karen Gasparyan

💻
Sergey Korchinskiy
Sergey Korchinskiy

🐛💻⚠️
Edygar Oliveira
Edygar Oliveira

💻🐛
epeicher
epeicher

🐛
François Chalifour
François Chalifour

💻⚠️📦
Maxim Malov
Maxim Malov

🐛💻
Enrique Piqueras
Enrique Piqueras

🤔
Oleksandr Fediashov
Oleksandr Fediashov

💻🚇🤔
Mikhail Bashurov
Mikhail Bashurov

💻🐛
Joshua Godi
Joshua Godi

💻
Kanitkorn Sujautra
Kanitkorn Sujautra

🐛💻
Jorge Moya
Jorge Moya

💻🐛
Jakub Jastrzębski
Jakub Jastrzębski

💻
Shukhrat Mukimov
Shukhrat Mukimov

💻
Jhonny Moreira
Jhonny Moreira

💻
stefanprobst
stefanprobst

💻⚠️
Louisa Spicer
Louisa Spicer

💻🐛
Ryō Igarashi
Ryō Igarashi

🐛💻
Ryan Lue
Ryan Lue

📖
Mateusz Leonowicz
Mateusz Leonowicz

💻
Dennis Thompson
Dennis Thompson

⚠️
Maksym Boytsov
Maksym Boytsov

💻
Sergey Skrynnikov
Sergey Skrynnikov

💻⚠️
Vincent Voyer
Vincent Voyer

📖
limejoe
limejoe

💻🐛
Manish Kumar
Manish Kumar

💻
Anang Fachreza
Anang Fachreza

📖💡
Nick Deom
Nick Deom

💻🐛
Clément Garbay
Clément Garbay

💻
Kaimin Huang
Kaimin Huang

💻🐛
David Welling
David Welling

💻🐛🤔🔬
chandrasekhar1996
chandrasekhar1996

🐛💻
Brendan Drew
Brendan Drew

💻
Jean Pan
Jean Pan

💻
Tom Jenkinson
Tom Jenkinson

🚇
Alice Hendicott
Alice Hendicott

💻🐛
Zach Davis
Zach Davis

💻🐛

This project follows theall-contributors specification.Contributions of any kind welcome!

LICENSE

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

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp