Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
downshift
Advanced tools
A set of primitives to build simple, flexible, WAI-ARIA compliant React autocomplete components
Downshift is a React library that provides a set of primitives to build simple, flexible, WAI-ARIA compliant enhanced input React components. Its major use cases include creating customizable dropdowns, comboboxes, and autocomplete/autosuggest inputs.
Autocomplete
This code sample demonstrates how to create a basic autocomplete input using Downshift. It includes a label, an input field, and a list of suggestions that appear as the user types.
{"import Downshift from 'downshift';\n\nfunction BasicAutocomplete() {\n return (\n <Downshift\n onChange={selection => alert(selection.value)}\n itemToString={item => (item ? item.value : '')}\n >\n {({\n getInputProps,\n getItemProps,\n getLabelProps,\n getMenuProps,\n isOpen,\n inputValue,\n highlightedIndex,\n selectedItem,\n getRootProps\n }) => (\n <div {...getRootProps({}, { suppressRefError: true })}>\n <label {...getLabelProps()}>Enter a fruit</label>\n <input {...getInputProps()} />\n <ul {...getMenuProps()}>\n {isOpen\n ? items\n .filter(item => !inputValue || item.value.includes(inputValue))\n .map((item, index) => (\n <li\n {...getItemProps({\n key: item.value,\n index,\n item,\n style: {\n backgroundColor:\n highlightedIndex === index ? 'lightgray' : 'white',\n fontWeight: selectedItem === item ? 'bold' : 'normal',\n },\n })}\n >\n {item.value}\n </li>\n ))\n : null}\n </ul>\n </div>\n )}\n </Downshift>\n );\n}\n\nconst items = [{ value: 'apple' }, { value: 'pear' }, { value: 'orange' }, { value: 'grape' }, { value: 'banana' }];"}
Dropdown
This code sample shows how to create a dropdown menu using Downshift. It includes a button to toggle the dropdown and a list of selectable items.
{"import Downshift from 'downshift';\n\nfunction BasicDropdown() {\n return (\n <Downshift\n onChange={selection => alert(selection.value)}\n itemToString={item => (item ? item.value : '')}\n >\n {({\n getToggleButtonProps,\n getMenuProps,\n isOpen,\n getItemProps,\n highlightedIndex,\n selectedItem\n }) => (\n <div>\n <button {...getToggleButtonProps()}>\n {selectedItem ? selectedItem.value : 'Select an item'}\n </button>\n <ul {...getMenuProps()}>\n {isOpen\n ? items.map((item, index) => (\n <li\n {...getItemProps({\n key: item.value,\n index,\n item,\n style: {\n backgroundColor:\n highlightedIndex === index ? 'lightgray' : 'white',\n fontWeight: selectedItem === item ? 'bold' : 'normal',\n },\n })}\n >\n {item.value}\n </li>\n ))\n : null}\n </ul>\n </div>\n )}\n </Downshift>\n );\n}\n\nconst items = [{ value: 'apple' }, { value: 'pear' }, { value: 'orange' }, { value: 'grape' }, { value: 'banana' }];"}
React Select is a flexible and beautiful Select Input control for ReactJS with multiselect, autocomplete, async and creatable support. It is similar to Downshift but offers more out-of-the-box features and styles, which can be easier for quick implementations but less flexible for extensive customization.
React Autocomplete is a component for building autocomplete functionalities in React applications. It is similar to Downshift in providing a low-level API for building custom autocomplete components, but it is less feature-rich and the API is not as extensive.
Material-UI provides a set of React components that implement Google's Material Design, including an Autocomplete component. While Downshift is more of a headless utility, Material-UI's Autocomplete comes with Material Design styles and more built-in functionalities, which might be preferable for applications seeking design consistency with Material Design.
Primitives to build simple, flexible, WAI-ARIA compliant React autocomplete/dropdown/select/combobox components
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 is a component that controls user interactions and state for you so you can create autocomplete/dropdown/select/etc. components. It uses a render function as children 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.
This module is distributed via npm which is bundled with node and
should be installed as one of your project's dependencies
:
npm install --save downshift
This package also depends on
react
andprop-types
. Please make sure you have those installed as well.
Note also this library supports
preact
out of the box. If you are usingpreact
then look in thedist/
folder and use the module you want with thepreact
suffix.
import Downshift from 'downshift'
function BasicAutocomplete({items, onChange}) {
return (
<Downshift onChange={onChange}>
{({
getInputProps,
getItemProps,
isOpen,
inputValue,
selectedItem,
highlightedIndex
}) => (
<div>
<input {...getInputProps({placeholder: 'Favorite color ?'})} />
{isOpen ? (
<div style={{border: '1px solid #ccc'}}>
{items
.filter(
i =>
!inputValue ||
i.toLowerCase().includes(inputValue.toLowerCase()),
)
.map((item, index) => (
<div
{...getItemProps({item})}
key={item}
style={{
backgroundColor:
highlightedIndex === index ? 'gray' : 'white',
fontWeight: selectedItem === item ? 'bold' : 'normal',
}}
>
{item}
</div>
))}
</div>
) : null}
</div>
)}
</Downshift>
)
}
function App() {
return (
<BasicAutocomplete
items={['apple', 'orange', 'carrot']}
onChange={selectedItem => console.log(selectedItem)}
/>
)
}
downshift
is the only component. It doesn't render anything itself, it just
calls the child function and renders that. Wrap everything in
<Downshift>{/* your function here! */}</Downshift>
.
any
| defaults tonull
Pass an item or an array of items that should be selected by default.
number
/null
| defaults tonull
This is the initial index to highlight when the menu first opens.
string
| defaults to''
This is the initial input value.
boolean
| defaults tofalse
This is the initial isOpen
value.
function(item: any)
| defaults to:i => (i == null ? '' : String(i))
Used to determine the string value for the selected item (which is used to
compute the inputValue
.
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 |
highlightedValue | any | The value of the highlighted item |
inputValue | string | The current input value |
isOpen | boolean | The isOpen state |
itemToString | function(any) | The itemToString function (see props) for getting the string value from one of the options |
previousResultCount | number | The total items showing in the dropdown the last time the status was updated |
resultCount | number | The total items showing in the dropdown |
selectedItem | any | The value of the currently selected item |
function(selectedItem: any, stateAndHelpers: object)
| optional, no useful default
Called when the user selects an 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 selectedstateAndHelpers
: This is the exact same thing you're children
prop
function is called with (see Child Callback Function)
function(changes: object, stateAndHelpers: object)
| optional, no useful default
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.stateAndHelpers
: This is the exact same thing you're children
prop
function is called with (see Child Callback Function)Tip: This function will be called any time any state is changed. The best way to determine whether any particular state was changed, you can use
changes.hasOwnProperty('propName')
.
Note: the
changes
object will also have atype
property that corresponds to aDownshift.stateChangeTypes
property. This is an experimental feature so it's not recommended to use it if you can avoid it. If you need it, please open an issue to discuss solidifying the API.
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
).
number
| control prop (read more about this in the "Control Props" section below)
The index that should be highlighted
string
| control prop (read more about this in the "Control Props" section below)
The value the input should have
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.
function({})
| required
This is called with an object. Read more about the properties of this object in the section "Child Callback Function"
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 child callback 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.
Note: This is very similar to how normal controlled components work elsewhere in react (like
<input />
). If you want to learn more about this concept, you can learn about that from this the "Controlled Components" lecture and exercises from React Training's Advanced React course.
This is where you render whatever you want to based on the state of downshift
.
The function is passed as the child prop:
<Downshift>{/* right here*/}</Downshift>
The properties of this object can be split into three categories as indicated below:
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 |
---|---|---|
getButtonProps | 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} />
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.
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 label
for
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 samehtmlFor
to yourlabel
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.
Basically just don't do this:
items.map(item => {
const props = getItemProps({item}) // we're calling it here
if (!shouldRenderItem(item)) {
return null // but we're not using props, and downshift things 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 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
.getButtonProps
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. The aria-label
prop is in
English. You should probably override this yourself so you can provide
translations:
<button {...getButtonProps({
'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 |
itemToString | function(item: any) | this is the same as the itemToString prop and is provided just as a helper |
otherStateToSet
refers to an object to set other internal state. It is recommended 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 the getInputProps input |
isOpen | boolean | the menu open state |
selectedItem | any | the currently selected item input |
Examples exist on codesandbox.io:
selectedItem
API).selectedItem
API).react-instantsearch
from AlgoliaGenieJS
(learn more about genie
here)react-tiny-virtual-list
fuzzaldrin-plus
(Fuzzy matching)If you would like to add an example, follow these steps:
downshift:example
You'll find other examples in the stories/examples
folder of the repo.
And you'll find
a live version of those examples here
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.
I also took a few ideas from the code in
react-autocomplete
and
jQuery UI's Autocomplete.
You can watch me build the first iteration of downshift
on YouTube:
You'll find more recordings of me working on downshift
on
my livestream YouTube playlist.
You can implement these other solutions using downshift
, but if
you'd prefer to use these out of the box solutions, then that's fine too:
Thanks goes to these people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
MIT
FAQs
🏎 A set of primitives to build simple, flexible, WAI-ARIA compliant React autocomplete, combobox or select dropdown components.
We found that downshift demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.