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

Overview

downshift ๐ŸŽ
downshift logo

Primitives to build simple, flexible, WAI-ARIA compliant React autocomplete, combobox or select dropdown components.

Read the docs | See the intro blog post | Listen to the Episode 79 of the Full Stack Radio podcast


Build Status Code Coverage downloads version MIT License

All Contributors PRs Welcome Chat Code of Conduct Join the community on Spectrum

Supports React and Preact size gzip size module formats: umd, cjs, and es

The problem

You need an autocomplete, a combobox or a select experience in your application and you want it to be accessible. You also want it to be simple and flexible to account for your use cases. Finally, it should follow the ARIA design pattern for a combobox or a select, depending on your use case.

This solution

The library offers a couple of solutions. The first solution, which is the one we recommend you to try first, is a set of React hooks. Each hook provides the stateful logic needed to make the corresponding component functional and accessible. Navigate to the documentation for each by using the links in the list below.

  • useSelect for a custom select component.
  • useCombobox for a combobox or autocomplete input.
  • useMultipleSelection for selecting multiple items in a select or a combobox, as well as deleting items from selection or navigating between the selected items.

The second solution is the Downshift component, which can also be used to create accessible combobox and select components, providing the logic in the form of a render prop. It served as inspiration for developing the hooks and it has been around for a while. It established a successful pattern for making components accessible and functional while giving developers complete freedom when building the UI.

The README on this page covers only the component while each hook has its own README page. You can navigate to the hooks page or go directly to the hook you need by using the links in the list above.

For examples on how to use the hooks or the Downshift component, check out our docsite!

Downshift

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

Table of Contents

Installation

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. Please make sure you have it installed as well.

Note also this library supports preact out of the box. If you are using preact then use the corresponding module in the preact/dist folder. You can even import Downshift from 'downshift/preact' ๐Ÿ‘

Usage

Try it out in the browser

import * as React from 'react'
import {render} from 'react-dom'
import Downshift from 'downshift'

const items = [
  {value: 'apple'},
  {value: 'pear'},
  {value: 'orange'},
  {value: 'grape'},
  {value: 'banana'},
]

render(
  <Downshift
    onChange={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>
        <div
          style={{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 an example without getRootProps.

Warning: The example without getRootProps is not fully accessible with screen readers as it's not possible to achieve the HTML structure suggested by ARIA. We recommend following the example with getRootProps. Examples on how to use Downshift component with and without getRootProps are on the docsite.

Downshift is the only component exposed by this package. It doesn't render anything itself, it just calls the render function and renders that. "Use a render prop!"! <Downshift>{downshift => <div>/* your JSX here! */</div>}</Downshift>.

Basic Props

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

children

function({}) | required

This is called with an object. Read more about the properties of this object in the 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 still needs a string representation for each one (e.g., to set inputValue).

Note: This callback must include a null check: it is invoked with null whenever the user abandons input via <Esc>.

onChange

function(selectedItem: any, stateAndHelpers: object) | optional, no useful default

Called when the selected item changes, either by the user selecting an item or the user clearing the selection. Called with the item that was selected or null and the new state of downshift. (see onStateChange for more info on stateAndHelpers).

  • selectedItem: The item that was just selected. null if the selection was cleared.
  • stateAndHelpers: This is the same thing your children function is called with (see Children Function)

stateReducer

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

๐Ÿšจ This is a really handy power feature ๐Ÿšจ

This function will be called each time downshift sets its internal state (or calls your onStateChange handler for control props). It allows you to modify the state change that will take place which can give you fine grain control over how the component interacts with user updates without having to use Control Props. It gives you the current state and the state that will be set, and you return the state that you want to set.

  • state: The full current state of downshift.
  • changes: These are the properties that are about to change. This also has a type property which you can learn more about in the stateChangeTypes section.
const ui = (
  <Downshift stateReducer={stateReducer}>{/* your callback */}</Downshift>
)

function stateReducer(state, changes) {
  // this prevents the menu from being closed when the user
  // selects an item with a keyboard or mouse
  switch (changes.type) {
    case Downshift.stateChangeTypes.keyDownEnter:
    case Downshift.stateChangeTypes.clickItem:
      return {
        ...changes,
        isOpen: state.isOpen,
        highlightedIndex: state.highlightedIndex,
      }
    default:
      return changes
  }
}

NOTE: This is only called when state actually changes. You should not attempt to use this to handle events. If you wish to handle events, put your event handlers directly on the elements (make sure to use the prop getters though! For example: <input onBlur={handleBlur} /> should be <input {...getInputProps({onBlur: handleBlur})} />). Also, your reducer function should be "pure." This means it should do nothing other than return the state changes you want to have happen.

Advanced Props

initialSelectedItem

any | defaults to null

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

initialInputValue

string | defaults to ''

This is the initial input value when downshift is initialized.

initialHighlightedIndex

number/null | defaults to defaultHighlightedIndex

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

initialIsOpen

boolean | defaults to defaultIsOpen

This is the initial isOpen value when downshift is initialized.

defaultHighlightedIndex

number/null | defaults to null

This is the value to set the highlightedIndex to anytime downshift is reset, when the selection is cleared, when an item is selected or when the inputValue is changed.

defaultIsOpen

boolean | defaults to false

This is the value to set the isOpen to anytime downshift is reset, when the the 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 new selectedItem has changed compared to the previous selectedItem and properly update Downshift's internal state.

getA11yStatusMessage

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

This function is passed as props to a Status component nested within and allows you to create your own assertive ARIA statuses.

A default getA11yStatusMessage function is provided that will check resultCount and return "No results are available." or if there are results , "resultCount results are available, use up and down arrow keys to navigate. Press Enter key to select."

The object you are passed to generate your status message has the following properties:

property type description
highlightedIndex number/null The currently highlighted index
highlightedItem any The value of the highlighted item
inputValue string The current input value
isOpen boolean The isOpen state
itemToString function(any) The itemToString function (see props) for getting the string value from one of the options
previousResultCount number The total items showing in the dropdown the last time the status was updated
resultCount number The total items showing in the dropdown
selectedItem any The value of the currently selected item

onSelect

function(selectedItem: any, stateAndHelpers: object) | optional, no useful default

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

  • selectedItem: The item that was just selected
  • stateAndHelpers: This is the same thing your children function is called with (see Children Function)

onStateChange

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. This also has a type property which you can learn more about in the stateChangeTypes section.
  • stateAndHelpers: This is the exact same thing your children function is called with (see Children Function)

Tip: This function will be called any time any state is changed. The best way to determine whether any particular state was changed, you can use changes.hasOwnProperty('propName').

NOTE: This is only called when state actually changes. You should not attempt to use this to handle events. If you wish to handle events, put your event handlers directly on the elements (make sure to use the prop getters though! For example: <input onBlur={handleBlur} /> should be <input {...getInputProps({onBlur: handleBlur})} />).

onInputValueChange

function(inputValue: string, stateAndHelpers: object) | optional, no useful default

Called whenever the input value changes. Useful to use instead or in combination of onStateChange when inputValue is a controlled prop to avoid issues with cursor positions.

  • inputValue: The current value of the input
  • stateAndHelpers: This is the same thing your children function is called with (see Children Function)

itemCount

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

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

highlightedIndex

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

The index that should be highlighted

inputValue

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

The value the input should have

isOpen

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

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

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 server rendering items (which each have an id prop generated based on the downshift id). For more information see the FAQ below.

inputId

string | defaults to a generated ID

Used for aria attributes and the id prop of the element (input) you use getInputProps with.

labelId

string | defaults to a generated ID

Used for aria attributes and the id prop of the element (label) you use getLabelProps with.

menuId

string | defaults to a generated ID

Used for aria attributes and the id prop of the element (ul) you use getMenuProps with.

getItemId

function(index) | defaults to a function that generates an ID based on the index

Used for aria attributes and the id prop of the element (li) you use getInputProps with.

environment

window | defaults to window

This prop is only useful if you're rendering downshift within a different window context from where your JavaScript is running; for example, an iframe or a shadow-root. If the given context is lacking document and/or add|removeEventListener on its prototype (as is the case for a shadow-root) then you will need to pass in a custom object that is able to provide access to these properties for downshift.

onOuterClick

function(stateAndHelpers: object) | optional

A helper callback to help control internal state of downshift like isOpen as mentioned in this issue. The same behavior can be achieved using onStateChange, but this prop is provided as a helper because it's a fairly common use-case if you're controlling the isOpen state:

const ui = (
  <Downshift
    isOpen={this.state.menuIsOpen}
    onOuterClick={() => this.setState({menuIsOpen: false})}
  >
    {/* your callback */}
  </Downshift>
)

This callback will only be called if isOpen is true.

scrollIntoView

function(node: HTMLElement, menuNode: HTMLElement) | defaults to internal implementation

This allows you to customize how the scrolling works when the highlighted index changes. It receives the node to be scrolled to and the root node (the root node you render in downshift). Internally we use compute-scroll-into-view so if you use that package then you wont be adding any additional bytes to your bundle :)

stateChangeTypes

There are a few props that expose changes to state (onStateChange and stateReducer). For you to make the most of these APIs, it's important for you to understand why state is being changed. To accomplish this, there's a type property on the changes object you get. This type corresponds to a Downshift.stateChangeTypes property.

The list of all possible values this type property can take is defined in this file and is as follows:

  • Downshift.stateChangeTypes.unknown
  • Downshift.stateChangeTypes.mouseUp
  • Downshift.stateChangeTypes.itemMouseEnter
  • Downshift.stateChangeTypes.keyDownArrowUp
  • Downshift.stateChangeTypes.keyDownArrowDown
  • Downshift.stateChangeTypes.keyDownEscape
  • Downshift.stateChangeTypes.keyDownEnter
  • Downshift.stateChangeTypes.clickItem
  • Downshift.stateChangeTypes.blurInput
  • Downshift.stateChangeTypes.changeInput
  • Downshift.stateChangeTypes.keyDownSpaceButton
  • Downshift.stateChangeTypes.clickButton
  • Downshift.stateChangeTypes.blurButton
  • Downshift.stateChangeTypes.controlledPropUpdatedSelectedItem
  • Downshift.stateChangeTypes.touchEnd

See stateReducer for a concrete example on how to use the type property.

Control Props

downshift manages its own state internally and calls your onChange and onStateChange handlers with any relevant changes. The state that downshift manages includes: isOpen, selectedItem, inputValue, and highlightedIndex. Your Children function (read more below) can be used to manipulate this state and can likely support many of your use cases.

However, if more control is needed, you can pass any of these pieces of state as a prop (as indicated above) and that state becomes controlled. As soon as this.props[statePropKey] !== undefined, internally, 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 Advanced React Component Patterns course

Children Function

This is where you render whatever you want to based on the state of downshift. You use it like so:

const ui = (
  <Downshift>
    {downshift => (
      // use downshift utilities and state here, like downshift.isOpen,
      // downshift.getInputProps, etc.
      <div>{/* more jsx here */}</div>
    )}
  </Downshift>
)

The properties of this downshift object can be split into three categories as indicated below:

prop getters

See the blog post about prop getters

NOTE: These prop-getters provide important aria- attributes which are very important to your component being accessible. It's recommended that you utilize these functions and apply the props they give you to your components.

These functions are used to apply props to the elements that you render. This gives you maximum flexibility to render what, when, and wherever you like. You call these on the element in question (for example: <input {...getInputProps()})). It's advisable to pass all your props to that function rather than applying them on the element yourself to avoid your props being overridden (or overriding the props returned). For example: getInputProps({onKeyUp(event) {console.log(event)}}).

property type description
getToggleButtonProps function({}) returns the props you should apply to any menu toggle button element you render.
getInputProps function({}) returns the props you should apply to the input element that you render.
getItemProps function({}) returns the props you should apply to any menu item elements you render.
getLabelProps function({}) returns the props you should apply to the label element that you render.
getMenuProps function({},{}) returns the props you should apply to the ul element (or root of your menu) that you render.
getRootProps function({},{}) returns the props you should apply to the root element that you render. It can be optional.

getRootProps

If you cannot render a div as the root element, then read this

Most of the time, you can just render a div yourself and Downshift will apply the props it needs to do its job (and you don't need to call this function). However, if you're rendering a composite component (custom component) as the root element, then you'll need to call getRootProps and apply that to your root element (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 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} />. It defaults to ref.

If you're rendering a composite component, Downshift checks that getRootProps is called and that refKey is a prop of the returned composite component. This is done to catch common causes of errors but, in some cases, the check could fail even if the ref is correctly forwarded to the root DOM component. In these cases, you can provide the object {suppressRefError : true} as the second argument to getRootProps to completely bypass the check.
Please use it with extreme care and only if you are absolutely sure that the ref is correctly forwarded otherwise Downshift will unexpectedly fail.
See #235 for the discussion that lead to this.

getInputProps

This method should be applied to the input you render. It is recommended that you pass all props as an object to this method which will compose together any of the event handlers you need to apply to the input while preserving the ones that downshift needs to apply to make the input behave.

There are no required properties for this method.

Optional properties:

  • disabled: If this is set to true, then no event handlers will be returned from getInputProps and a disabled prop will be returned (effectively disabling the input).

getLabelProps

This method should be applied to the label you render. It is useful for ensuring that the for attribute on the <label> (htmlFor as a react prop) is the same as the id that appears on the input. If no htmlFor is provided (the normal case) 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: 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 a map expression. This handles the proper ARIA roles and attributes.

Optional properties:

  • refKey: if you're rendering a composite component, that component will need to accept a prop which it forwards to the root DOM element. Commonly, folks call this innerRef. So you'd call: getMenuProps({refKey: 'innerRef'}) and your composite component would forward like: <ul ref={props.innerRef} />. However, if you are just rendering a primitive component like <div>, there is no need to specify this property. It defaults to ref.

    Please keep in mind that menus, for accessibility purposes, should always be rendered, regardless of whether you hide it or not. Otherwise, getMenuProps may throw error if you unmount and remount the menu.

  • aria-label: By default the menu will add an aria-labelledby that refers to the <label> rendered with getLabelProps. However, if you provide aria-label to give a more specific label that describes the options available, then aria-labelledby will not be provided and screen readers can use your aria-label instead.

In some cases, you might want to completely bypass the refKey check. Then you can provide the object {suppressRefError : true} as the second argument to getMenuProps. Please use it with extreme care and only if you are absolutely sure that the ref is correctly forwarded otherwise Downshift will unexpectedly fail.

<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 this element whether or not downshift is in an isOpen state.

getItemProps

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

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

What do you mean by impure function?

Basically just don't do this:

items.map(item => {
  const props = getItemProps({item}) // we're calling it here
  if (!shouldRenderItem(item)) {
    return null // 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 a particular item.

Optional properties:

  • index: This is how downshift keeps track of your item when updating the highlightedIndex as the user keys around. By default, downshift will assume the index is the order in which you're calling getItemProps. This is often good enough, but if you find odd behavior, try setting this explicitly. It's probably best to be explicit about index when using a windowing library like react-virtualized.
  • disabled: If this is set to true, then all of the downshift item event handlers will be omitted. Items will not be highlighted when hovered, and items will not be selected when clicked.

getToggleButtonProps

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

Optional properties:

  • disabled: If this is set to true, then all of the downshift button event handlers will be omitted (it wont toggle the menu when clicked).
  • aria-label: The aria-label prop is in English. You should probably override this yourself so you can provide translations:
const myButton = (
  <button
    {...getToggleButtonProps({
      'aria-label': translateWithId(isOpen ? 'close.menu' : 'open.menu'),
    })}
  />
)

actions

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

property type description
clearSelection function(cb: Function) clears the selection
clearItems function() Clears downshift's record of all the items. Only really useful if you render your items asynchronously within downshift. See #186
closeMenu function(cb: Function) closes the menu
openMenu function(cb: Function) opens the menu
selectHighlightedItem function(otherStateToSet: object, cb: Function) selects the item that is currently highlighted
selectItem function(item: any, otherStateToSet: object, cb: Function) selects the given item
selectItemAtIndex function(index: number, otherStateToSet: object, cb: Function) selects the item at the given index
setHighlightedIndex function(index: number, otherStateToSet: object, cb: Function) call to set a new highlighted index
toggleMenu function(otherStateToSet: object, cb: Function) toggle the menu open state
reset function(otherStateToSet: object, cb: Function) this resets downshift's state to a reasonable default
setItemCount function(count: number) this sets the itemCount. Handy in situations where you're using windowing and the items are loaded asynchronously from within downshift (so you can't use the itemCount prop.
unsetItemCount function() this unsets the itemCount which means the item count will be calculated instead by the itemCount prop or based on how many times you call getItemProps.
setState function(stateToSet: object, cb: Function) This is a general setState function. It uses downshift's internalSetState function which works with control props and calls your onSelect, onChange, etc. (Note, you can specify a type which you can reference in some other APIs like the stateReducer).

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

state

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

property type description
highlightedIndex number / null the currently highlighted item
inputValue string / null the current value of the getInputProps input
isOpen boolean the menu open state
selectedItem any the currently selected item input

props

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

Event Handlers

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

default handlers

  • ArrowDown: if menu is closed, opens it and moves the highlighted index to defaultHighlightedIndex + 1, if defaultHighlightedIndex is provided, or to the top-most item, if not. If menu is open, it moves the highlighted index down by 1. If the shift key is held when this event fires, the highlighted index will jump down 5 indices instead of 1. NOTE: if the current highlighted index 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 to defaultHighlightedIndex - 1, if defaultHighlightedIndex is provided, or to the bottom-most item, if not. If menu is open, moves the highlighted index up by 1. If the shift key is held when this event fires, the highlighted index will jump up 5 indices instead of 1. NOTE: if the current highlighted index is within 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 is open, 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 the menu is open, the usual 'Enter' event is prevented by Downshift's default implicit enter handler; so, for example, a form submission event will not work as one might expect (though if the menu is closed the form submission will work normally). See below for customizing the handlers.

  • Escape: will clear downshift's state. This means that highlightedIndex will be set to the defaultHighlightedIndex and the isOpen state will be set to the defaultIsOpen. If isOpen is already false, the inputValue will be set to an empty string and selectedItem will be set to null

customizing handlers

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

const ui = (
  <Downshift>
    {({getInputProps}) => (
      <input
        {...getInputProps({
          onKeyDown: event => {
            // your handler code
          },
        })}
      />
    )}
  </Downshift>
)

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

const ui = (
  <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, in favor of your own, you can bypass prop getters:

const ui = (
  <Downshift>
    {({getInputProps}) => (
      <input
        {...getInputProps()}
        onKeyDown={event => {
          // your handler code
        }}
      />
    )}
  </Downshift>
)

Utilities

resetIdCounter

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

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

import {resetIdCounter} from 'downshift';

resetIdCounter()
ReactDOMServer.renderToString(...);

React Native

Since Downshift renders it's UI using render props, Downshift supports rendering on React Native with ease. Use components like <View>, <Text>, <TouchableOpacity> and others inside of your render method to generate awesome autocomplete, dropdown, or selection components.

Gotchas

  • Your root view will need to either pass a ref to getRootProps or call getRootProps with { suppressRefError: true }. This ref is used to catch a common set of errors around composite components. Learn more in getRootProps.
  • When using a <FlatList> or <ScrollView>, be sure to supply the keyboardShouldPersistTaps prop to ensure that your text input stays focus, while allowing for taps on the touchables rendered for your items.

Advanced React Component Patterns course

Kent C. Dodds has created learning material based on the patterns implemented in this component. You can find it on various platforms:

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

Examples

๐Ÿšจ We're in the process of moving all examples to the downshift-examples repo (which you can open, interact with, and contribute back to live on codesandbox)

๐Ÿšจ We're also in the process of updating our examples from the downshift-docs repo which is actually used to create our docsite at downshift-js.com). Make sure to check it out for the most relevant Downshift examples or try out the new hooks 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 by ARIA-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 and match-sorter for filtering the items.
  4. typeahead - Shows how to control the selectedItem so the selected item can be one of your items or whatever the user types.
  5. multi-select - Shows how to create a MultiDownshift component that allows for an array of selectedItems 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 to provide the downshift dropdown component with the functionality of being able to 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 asynchronously loading items, multiple selection, and windowing (with react-virtualized)
  • Downshift HOC and Compound Components - An example of how to implementat compound components with React.createContext and a downshift higher order component. This is generally not recommended because the render prop API exported by downshift is generally good enough for everyone, but there's nothing technically wrong with doing something like this.

Old Examples exist on codesandbox.io:

๐Ÿšจ This is a great contribution opportunity! These are examples that have not yet been migrated to downshift-examples. You're more than welcome to make PRs to the examples repository to move these examples 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 automatically generated id and/or htmlFor prop you get from getInputProps and getLabelProps (respectively). It could also be from the automatically generated id prop you get from getItemProps (though this is not likely as you're probably not rendering any items when rendering a downshift component on the server).

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

Alternatively you could provide your own ids via the id props where you render <Downshift />:

const ui = (
  <Downshift
    id="autocomplete"
    labelId="autocomplete-label"
    inputId="autocomplete-input"
    menuId="autocomplete-menu"
  >
    {({getInputProps, getLabelProps}) => <div>{/* your UI */}</div>}
  </Downshift>
)

Inspiration

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

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.

Other Solutions

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:

Bindings for ReasonML

If you're developing some React in ReasonML, check out the Downshift bindings for that.

Contributors

Thanks goes to these people (emoji key):


Kent C. Dodds

๐Ÿ’ป ๐Ÿ“– ๐Ÿš‡ โš ๏ธ ๐Ÿ‘€ ๐Ÿ“ ๐Ÿ› ๐Ÿ’ก ๐Ÿค” ๐Ÿ“ข

Ryan Florence

๐Ÿค”

Jared Forsyth

๐Ÿค” ๐Ÿ“–

Jack Moore

๐Ÿ’ก

Travis Arnold

๐Ÿ’ป ๐Ÿ“–

Marcy Sutton

๐Ÿ› ๐Ÿค”

Jeremy Gayed

๐Ÿ’ก

Haroen Viaene

๐Ÿ’ก

monssef

๐Ÿ’ก

Federico Zivolo

๐Ÿ“–

Divyendu Singh

๐Ÿ’ก ๐Ÿ’ป ๐Ÿ“– โš ๏ธ

Muhammad Salman

๐Ÿ’ป

Joรฃo Alberto

๐Ÿ’ป

Bernard Lin

๐Ÿ’ป ๐Ÿ“–

Geoff Davis

๐Ÿ’ก

Anup

๐Ÿ“–

Ferdinand Salis

๐Ÿ› ๐Ÿ’ป

Kye Hohenberger

๐Ÿ›

Julien Goux

๐Ÿ› ๐Ÿ’ป โš ๏ธ

Joachim Seminck

๐Ÿ’ป

Jesse Harlin

๐Ÿ› ๐Ÿ’ก

Matt Parrish

๐Ÿ”ง ๐Ÿ‘€

thom

๐Ÿ’ป

Vu Tran

๐Ÿ’ป

Codie Mullins

๐Ÿ’ป ๐Ÿ’ก

Mohammad Rajabifard

๐Ÿ“– ๐Ÿค”

Frank Tan

๐Ÿ’ป

Kier Borromeo

๐Ÿ’ก

Paul Veevers

๐Ÿ’ป

Ron Cruz

๐Ÿ“–

Rick McGavin

๐Ÿ“–

Jelle Versele

๐Ÿ’ก

Brent Ertz

๐Ÿค”

Justice Mba

๐Ÿ’ป ๐Ÿ“– ๐Ÿค”

Mark Ellis

๐Ÿค”

usอกanฬธdfอ˜rienอœdsอ 

๐Ÿ› ๐Ÿ’ป โš ๏ธ

Robin Drexler

๐Ÿ› ๐Ÿ’ป

Arturo Romero

๐Ÿ’ก

yp

๐Ÿ› ๐Ÿ’ป โš ๏ธ

Dave Garwacke

๐Ÿ“–

Ivan Pazhitnykh

๐Ÿ’ป โš ๏ธ

Luis Merino

๐Ÿ“–

Andrew Hansen

๐Ÿ’ป โš ๏ธ ๐Ÿค”

John Whiles

๐Ÿ’ป

Justin Hall

๐Ÿš‡

Pete Nykรคnen

๐Ÿ‘€

Jared Palmer

๐Ÿ’ป

Philip Young

๐Ÿ’ป โš ๏ธ ๐Ÿค”

Alexander Nanberg

๐Ÿ“– ๐Ÿ’ป

Pete Redmond

๐Ÿ›

Nick Lavin

๐Ÿ› ๐Ÿ’ป โš ๏ธ

James Long

๐Ÿ› ๐Ÿ’ป

Michael Ball

๐Ÿ› ๐Ÿ’ป โš ๏ธ

CAVALEIRO Julien

๐Ÿ’ก

Kim Grรถnqvist

๐Ÿ’ป โš ๏ธ

Sijie

๐Ÿ› ๐Ÿ’ป

Dony Sukardi

๐Ÿ’ก ๐Ÿ’ฌ ๐Ÿ’ป โš ๏ธ

Dillon Mulroy

๐Ÿ“–

Curtis Tate Wilkinson

๐Ÿ’ป

Brice BERNARD

๐Ÿ› ๐Ÿ’ป

Tony Xu

๐Ÿ’ป

Anthony Ng

๐Ÿ“–

S S

๐Ÿ’ฌ ๐Ÿ’ป ๐Ÿ“– ๐Ÿค” โš ๏ธ

Austin Tackaberry

๐Ÿ’ฌ ๐Ÿ’ป ๐Ÿ“– ๐Ÿ› ๐Ÿ’ก ๐Ÿค” ๐Ÿ‘€ โš ๏ธ

Jean Duthon

๐Ÿ› ๐Ÿ’ป

Anton Telesh

๐Ÿ› ๐Ÿ’ป

Eric Edem

๐Ÿ’ป ๐Ÿ“– ๐Ÿค” โš ๏ธ

Austin Wood

๐Ÿ’ฌ ๐Ÿ“– ๐Ÿ‘€

Mark Murray

๐Ÿš‡

Gianmarco

๐Ÿ› ๐Ÿ’ป

Emmanuel Pastor

๐Ÿ’ก

dalehurwitz

๐Ÿ’ป

Bogdan Lobor

๐Ÿ› ๐Ÿ’ป

Luke Herrington

๐Ÿ’ก

Brandon Clemons

๐Ÿ’ป

Kieran

๐Ÿ’ป

Brushedoctopus

๐Ÿ› ๐Ÿ’ป

Cameron Edwards

๐Ÿ’ป โš ๏ธ

stereobooster

๐Ÿ’ป โš ๏ธ

Trevor Pierce

๐Ÿ‘€

Xuefei Li

๐Ÿ’ป

Alfred Ringstad

๐Ÿ’ป

D[oa]vid Weisz

๐Ÿ’ป

Royston Shufflebotham

๐Ÿ› ๐Ÿ’ป

Michaรซl De Boey

๐Ÿ’ป

Henry

๐Ÿ’ป

Andrew Walton

๐Ÿ› ๐Ÿ’ป โš ๏ธ

Arthur Denner

๐Ÿ’ป

Cody Olsen

๐Ÿ’ป

Thomas Ladd

๐Ÿ’ป

lixualinta

๐Ÿ’ป

Jacob Cofman

๐Ÿ’ป

Joshua Freedman

๐Ÿ’ป

Amy

๐Ÿ’ก

Rogin Farrer

๐Ÿ’ป

Dmitrii Kanatnikov

๐Ÿ’ป

Dallon Feldner

๐Ÿ› ๐Ÿ’ป

Samuel Fuller Thomas

๐Ÿ’ป

Ryan Castner

๐Ÿ’ป

Silviu Alexandru Avram

๐Ÿ› ๐Ÿ’ป โš ๏ธ

Anton Volkov

๐Ÿ’ป โš ๏ธ

Keegan Street

๐Ÿ› ๐Ÿ’ป

Manuel Duguรฉ

๐Ÿ’ป

Max Karadeniz

๐Ÿ’ป

Gonzalo Beviglia

๐Ÿ› ๐Ÿ’ป ๐Ÿ‘€

Brian Kilrain

๐Ÿ› ๐Ÿ’ป โš ๏ธ ๐Ÿ“–

Gerd Zschaler

๐Ÿ’ป ๐Ÿ›

Karen Gasparyan

๐Ÿ’ป

Sergey Korchinskiy

๐Ÿ› ๐Ÿ’ป โš ๏ธ

Edygar Oliveira

๐Ÿ’ป ๐Ÿ›

epeicher

๐Ÿ›

Franรงois Chalifour

๐Ÿ’ป โš ๏ธ ๐Ÿ“ฆ

Maxim Malov

๐Ÿ› ๐Ÿ’ป

Enrique Piqueras

๐Ÿค”

Oleksandr Fediashov

๐Ÿ’ป ๐Ÿš‡ ๐Ÿค”

Mikhail Bashurov

๐Ÿ’ป ๐Ÿ›

Joshua Godi

๐Ÿ’ป

Kanitkorn Sujautra

๐Ÿ› ๐Ÿ’ป

Jorge Moya

๐Ÿ’ป ๐Ÿ›

Jakub Jastrzฤ™bski

๐Ÿ’ป

Shukhrat Mukimov

๐Ÿ’ป

Jhonny Moreira

๐Ÿ’ป

stefanprobst

๐Ÿ’ป โš ๏ธ

Louisa Spicer

๐Ÿ’ป ๐Ÿ›

Ryล Igarashi

๐Ÿ› ๐Ÿ’ป

Ryan Lue

๐Ÿ“–

Mateusz Leonowicz

๐Ÿ’ป

Dennis Thompson

โš ๏ธ

Maksym Boytsov

๐Ÿ’ป

Sergey Skrynnikov

๐Ÿ’ป โš ๏ธ

Vincent Voyer

๐Ÿ“–

limejoe

๐Ÿ’ป ๐Ÿ›

Manish Kumar

๐Ÿ’ป

Anang Fachreza

๐Ÿ“– ๐Ÿ’ก

Nick Deom

๐Ÿ’ป ๐Ÿ›

Clรฉment Garbay

๐Ÿ’ป

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

LICENSE

MIT

Comments
  • Name change

    Name change

    Pertaining to https://github.com/kentcdodds/react-autocompletely/issues/1 I personally think it would be beneficial to choose a name that promotes this library for multiple use cases. I think by naming it anything with autocomplete could paint the library into a corner. I'd love to see Dropdown, Select and other cool components made with this. The hard part is I have no idea what a new name could be ๐Ÿ’ฉ

    Some quick ones:

    • rechoose - react + choose
    • reelect - react + elect (maybe just elect by itself?)
    • repick - react + pick
    • picknic - ๐Ÿคทโ€โ™‚๏ธ
    question 
    opened by souporserious 60
  • Help make examples

    Help make examples

    Latest Update:

    Alrighty! We're getting really close now! Just need to tie up some loose ends and make sure we cover all the use cases we want to (ALL OF THEM).

    We've released an official "release candidate"

    You can install it with:

    npm install --save downshift@rc
    

    If you want to help, try implementing an autocomplete/combobox/multi-select/etc. with downshift. You can:

    1. fork the example codesandbox here
    2. give it a good title and description
    3. Update the version (go to dependencies, type downshift for the "package name" and rc for the "version"). Do this even though it already appears in the list of dependencies.
    4. Add the downshift:example tag. That way it shows up in this search
    5. Ping us here when you're done. Thanks!

    Old Update:

    Hey folks! :wave: now that we've released a beta version, it's much easier to make examples. Now you can make them right in the browser :tada: (thank you @CompuIves!!!)

    So, if you've made an example already, would you mind forking this example: http://kcd.im/rac-example and updating it to your example? Then give it a good title and description and add the react-autocompletely:example tag That way it shows up in this search

    I'll add a link to that in the README so folks can go see all the awesome examples you all make. Thanks!!!


    Old stuff

    Hey :wave:

    We need help making examples. I've scaffolded out things for the examples already, but we need more and need to improve the ones that we already do have. Here's a quick rundown of how to get up and running with the examples:

    git clone https://github.com/kentcdodds/react-autocompletely.git
    cd react-autocompletely
    npm install
    cd examples
    npm install
    npm start
    

    Then open http://localhost:3000/example-name

    In the examples directory, you'll find a pages directory. Each of those has an index.js file which is rendered at that route. For example, semantic-ui/index.js will be rendered at: http://localhost:3000/semantic-ui

    So, the idea for these examples is they can be examples of just about anything. I have a few in there to show examples of how to implement the API or look and feel that other libraries have. That's mostly to demonstrate the power of the primitives available in react-autocomplete.

    Feel free to comment here on what example you're working on. You can update an existing example or create a new one. Just let us know so we don't step on each others toes. Thanks!

    Oh, and one other thing, right now this repo is private because I need to clear things with legal before we open source it as a PayPal library. So I have to give you commit access. Regardless of that, if you could, please still make forks and don't commit directly to the repo :) Thanks!

    help wanted 
    opened by kentcdodds 60
  • Sometimes items is an empty array when clicking an item

    Sometimes items is an empty array when clicking an item

    • downshift version: latest
    • node version: 8.4
    • npm (or yarn) version: 5.3.0

    What you did: Select an item per left mouse click

    What happened: Most of the time it would select the item as expected. However sometimes it will not.

    kapture 2017-09-12 at 17 37 48

    Reproduction repository: https://codesandbox.io/s/l2yk1qqqrm

    Problem description:* This is due to the fact that at the point of time the item is clicked it has not yet been added to the items array.

    Suggested solution: No idea yet how to solve this.

    opened by ferdinandsalis 41
  • feat: multi-select hook for useSelect and useCombobox

    feat: multi-select hook for useSelect and useCombobox

    Is it possible to use the useSelect hook for a list that allows selecting multiple options? Is there an example of this? It seems like it only has one selectedItem prop that just takes a single item, so it is fine to manage the "currently selected items" state myself?

    enhancement needs discussion released wip 
    opened by Daniel15 37
  • How to make downshift just behave like text box if user does not want to select from selection

    How to make downshift just behave like text box if user does not want to select from selection

    I am trying to figure how do I make Downshift Input just behave like a text box if there are no suggestions or user wants to enter something free text and ignore suggestion .

    Any thoughts ?

    opened by kavink 36
  • inputValue is set to empty string on select of already selected item

    inputValue is set to empty string on select of already selected item

    • downshift version: 2.0.0 +
    • node version: 9.11.1
    • npm (or yarn) version: yarn 1.7

    Relevant code or config See updated Custom select with downshift example - https://codesandbox.io/s/18ll7293vq I updated version of Downshift to 2.0.0 and made Downshift using controlled selectedItem prop.

    What you did: I tried to use Downshift for a custom select component according to examples.

    What happened: Everything works, apart from one thing - if you have an item selected, and then you open dropdown again and you pick the same item, for some reason inputValue is set to empty string. However, if you select a different option, then inputValue is updated correctly to itemToString of a newly selected option

    Reproduction repository: https://codesandbox.io/s/18ll7293vq

    Problem description: Problem described above started to happen since version 2.0.0, for v1.31.16 it works as expected - you can downgrade codesandbox to v1.31.16 and it will work correctly.

    bug help wanted 
    opened by klis87 34
  • [WIP] Add support for React Native as a target

    [WIP] Add support for React Native as a target

    What: Adds support for using ๐ŸŽ in React Native. Closes #185.

    Why: Prior to this, React Native could not be targeted, as there are DOM-specific codepaths. This ensures those codepaths are not followed on React Native.

    How: Added the basic downshift implementation into a React Native app and started hammering out errors, stripping away DOM-related code.

    Checklist:

    None of these are done yet! This is a work-in-progress. Putting this up for review as a check to make sure I'm headed in the right direction.

    • [ ] Documentation
    • [ ] Tests
    • [ ] Ready to be merged
    • [ ] Added myself to contributors table
    opened by eliperkins 34
  • Fine tune babel config

    Fine tune babel config

    I tried react-autocompletely with a create-react-app project, and attempted to build it (i.e. npm run build), but received this error:

    Failed to compile.
    
    static/js/main.9d2e66e4.js from UglifyJs
    Unexpected token: punc (,) [./~/react-autocompletely/dist/menu-status.js:60,0][static/js/main.9d2e66e4.js:56374,19]
    
    error Command failed with exit code 1.
    

    I believe babel config would probably need some fine tuning: https://github.com/paypal/react-autocompletely/blob/cfc1ffffe38bac9d89555998add9d5ac2024ea40/.babelrc

    opened by dashed 33
  • Accessibility status changes

    Accessibility status changes

    Mainly addressing https://github.com/paypal/downshift/issues/621 but also the process overall. I had a hunch about what caused Safari not to read the options, and it was the fact that we are using aria-selected wrong (true, many use it this way).

    According to Aria, aria-selected marks the currently highlighted option in the list, not the actual selected item (or items if we have multiple choice). Came across this github issue and also the aria spec here, specifically at the Listbox Popup section.

    Changes I made, explained.

    1. When user navigates through the options, don't update the aria-live message anymore. Will leave the default screen reader behaviour in reading (Black, 1 of 6).
    2. Will fix Safari by adding aria-selected="true" to the highlighter element. Bad news is that it will break the implementations that use it incorrectly. Good news is that we can add the highlight style using that class, rather than using the style attribute (not sure if an improvement, but saw this being done many times).
    3. Will narrate how many options exist any time their number change. I think it makes sense that the user should be notified about this. Use case: going through the options (so having a highlighted item) and also changing the query string in the input (so the number of options may change).
    4. Making these announcements polite. It is not a warning / error message, like 'Form not submitted/Problem with connection', we should not interrupt. For instance, navigating to the dropdown, pressing Down will first narrate the first option, and then will narrate the number of options.
    5. Some minor changes related to the actual message. I got these suggestions from the accessibility team I am working with, I think they are a nice touch.
    6. Added highlightedItem to the TS types A11yStatusMessageOptions<Item>, as it was missing, and in downshift.js that method is also called with the highlightedItem.
    7. Changed the unit tests to match new behaviour.
    8. Nit: const status = this.props.getA11yStatusMessage({ was called with highlighted item twice, once with the one from array, then was overridden with the one from state. I removed the first, please take a look and see if it correct.
    released 
    opened by silviuaavram 32
  • More flexibility, less API?

    More flexibility, less API?

    What do folks think about doing something like this:

    const ui = (
      <Autocomplete getValue={a => a.title}>
        {({getInputProps, getItemProps, isOpen}) =>
          <div>
            <input
              {...getInputProps({
                placeholder: 'hello world',
                ref: node => (this.myOwnReference = node),
              })}
            />
            {isOpen
              ? <div>
                  {items.map(i =>
                    <article {...getItemProps({key: i.id})}>
                      {i.articleDetails}
                    </article>
                  )}
                </div>
              : null}
          </div>}
      </Autocomplete>
    )
    

    The entire API consists of a handful of props you pass to Autocomplete and a handful of arguments you receive in that callback. No need for props like component because you render the component yourself and you call a function to get the props to apply to the component so it hooks up properly with the autocomplete. In addition, there's no need of using the context API anymore which make the implementation a little nicer.

    I'm actually pretty excited by this idea (originally inspired by @jaredly a week ago or so). I tried it and it didn't work very well, but now I think I know how to make it work and I think it'll be great. Minimizing the API and enhance the flexibility/simplicity of the thing. I'm probably going to try to implement this as soon as I can. Just wanted to hear your thoughts :smile:

    opened by kentcdodds 27
  • Implement support for React Native

    Implement support for React Native

    • downshift version: 1.5.0
    • node version: 8.3.0
    • npm (or yarn) version: yarn 1.0.1

    Relevant code or config

    import React from 'react';
    import { Input } from 'native-base';
    import Downshift from 'downshift'
    
    export default function AutocompleteInput({items, onChange}) {
        return (
            <Downshift onChange={onChange}>
                {({
                    getInputProps,
                    getItemProps,
                    getRootProps,
                    isOpen,
                    inputValue,
                    selectedItem,
                    highlightedIndex
                  }) => {
                    return (
                        <Input {...getRootProps({refKey: "categoryTesting"})} {...getInputProps()} />
                    );
                }}
            </Downshift>
        )
    }
    

    What you did: Added an autocomplete input component to my React Native project and attached Downshift to it.

    What happened:

    window.addEventListener is not a function. (In 'window.addEventListener('mousedown', onMouseDown)', 'window.addEventListener' is undefined)

    componentDidMount downshift.cjs.js:699:30 measureLifeCyclePerf ReactNativeStack-dev.js:1610:15 ReactNativeStack-dev.js:1657:33 notifyAll ReactNativeStack-dev.js:2121:107 close ReactNativeStack-dev.js:2138:8 closeAll ReactNativeStack-dev.js:1412:101 perform ReactNativeStack-dev.js:1388:52 batchedMountComponentIntoNode ReactNativeStack-dev.js:2004:24 perform ReactNativeStack-dev.js:1382:99 renderComponent ReactNativeStack-dev.js:2032:45 renderApplication renderApplication.js:34:4 runApplication AppRegistry.js:191:26 __callFunction MessageQueue.js:266:47 MessageQueue.js:103:26 __guard MessageQueue.js:231:6 callFunctionReturnFlushedQueue MessageQueue.js:102:17

    image1

    Reproduction repository: https://github.com/gricard/downshift-reactnative-repro

    Problem description: Downshift does not currently have support for the React Native environment, which has some minor differences to running in the browser.

    Suggested solution: I had a brief discussion about the issue with Kent, and he provided these three links which are areas where there will need to be changes in order to support React Native:

    https://github.com/paypal/downshift/blob/a1490f070575ffcd71dac8c063fe7e092f840a67/src/downshift.js#L208-L209

    https://github.com/paypal/downshift/blob/a1490f070575ffcd71dac8c063fe7e092f840a67/src/downshift.js#L150

    https://github.com/paypal/downshift/blob/a1490f070575ffcd71dac8c063fe7e092f840a67/src/downshift.js#L655-L681

    I'd like to take a shot at implementing a fix and providing a PR. I'm looking for guidance on that, as this is the first time I've taken the time to attempt contributing back to a project, and I'm also fairly new at RN as well.

    (FYI, there is no CODE_OF_CONDUCT.md file that is mentioned in the issue template)

    help wanted react native 
    opened by gricard 26
  • fix: set `browserlist` so that js files are transpiled

    fix: set `browserlist` so that js files are transpiled

    What:

    This PR changes the JS to be transpiled.

    Why:

    Unfortunately at the moment we cannot use downshift because it is tripping up our storybook and webpack builds due to some syntax that is too new, such as ??.

    How:

    Configure the browserlist in package.json.

    Checklist:

    • [ ] Documentation N/A
    • [ ] Tests N/A
    • [ ] TypeScript Types N/A
    • [ ] Flow Types N/A
    • [x] Ready to be merged
    opened by tjenkinson 0
  • v8

    v8

    List of deliverables:

    • [ ] Replace open on focus with toggle on input click for useCombobox. https://github.com/downshift-js/downshift/issues/1439
    • [ ] Rewrite the status message functionality to contain only getA11yStatusMessage, for all hooks, with cleanup. https://github.com/downshift-js/downshift/issues/1322 https://github.com/downshift-js/downshift/issues/1298 https://github.com/downshift-js/downshift/issues/1244 https://github.com/downshift-js/downshift/issues/1227
    • [ ] Create the hooks from https://github.com/downshift-js/downshift/issues/1233.
    • [ ] Create the hooks from https://github.com/downshift-js/downshift/issues/1450.
    • [ ] Types update for onChange https://github.com/downshift-js/downshift/issues/1225
    • [ ] isItemDisabled https://github.com/downshift-js/downshift/issues/1176
    • [ ] aria-selected only for selected item, not highlighted item, in useCombobox https://github.com/downshift-js/downshift/issues/935.
    • [ ] React 18 useId changes from https://github.com/downshift-js/downshift/pull/1445
    BREAKING CHANGE wip 
    opened by silviuaavram 0
  • Japanese IME not working when controlling `inputValue` in `useCombobox`

    Japanese IME not working when controlling `inputValue` in `useCombobox`

    • downshift version: 6.1.12
    • node version: 14.19.0
    • yarn version: 1.22.17

    Relevant code or config

    type Book = { author: string; title: string };
    
    const books: Book[] = [
      { author: 'Harper Lee', title: 'To Kill a Mockingbird' },
      { author: 'Lev Tolstoy', title: 'War and Peace' },
      { author: 'Fyodor Dostoyevsy', title: 'The Idiot' },
      { author: 'Oscar Wilde', title: 'A Picture of Dorian Gray' },
      { author: 'George Orwell', title: '1984' },
      { author: 'Jane Austen', title: 'Pride and Prejudice' },
      { author: 'Marcus Aurelius', title: 'Meditations' },
      { author: 'Fyodor Dostoevsky', title: 'The Brothers Karamazov' },
      { author: 'Lev Tolstoy', title: 'Anna Karenina' },
      { author: 'Fyodor Dostoevsky', title: 'Crime and Punishment' },
    ];
    
    function getBooksFilter(inputValue: string | undefined) {
      return function booksFilter(book: Book) {
        return (
          !inputValue ||
          book.title.toLowerCase().includes(inputValue) ||
          book.author.toLowerCase().includes(inputValue)
        );
      };
    }
    export const Example = () => {
      const [items, setItems] = React.useState(books);
      const [inputValue, setInputValue] = React.useState('');
      const {
        isOpen,
        getToggleButtonProps,
        getLabelProps,
        getMenuProps,
        getInputProps,
        getItemProps,
        getComboboxProps,
      } = useCombobox<Book>({
        onInputValueChange(chg) {
          setInputValue(chg.inputValue || '');
          setItems(books.filter(getBooksFilter(chg.inputValue)));
        },
        inputValue, // Controlling inputValue here introduces IME composition issue
        items,
        itemToString(item) {
          return item ? item.title : '';
        },
      });
    
      return (
        <div>
          <div>
            <label {...getLabelProps()}>Choose your favorite book:</label>
            <div {...getComboboxProps()}>
              <input placeholder="Best book ever" {...getInputProps()} />
              <button
                aria-label="toggle menu"
                type="button"
                {...getToggleButtonProps()}
              >
                {isOpen ? <>&#8593;</> : <>&#8595;</>}
              </button>
            </div>
          </div>
          <ul {...getMenuProps()}>
            {isOpen &&
              items.map((item, index) => (
                <li
                  key={`${item.title}${index}`}
                  {...getItemProps({ item, index })}
                >
                  <span>{item.title}</span>
                  <span>{item.author}</span>
                </li>
              ))}
          </ul>
        </div>
      );
    };
    

    What you did: When entering Japanese (or any IME language) into a combobox that controls inputValue, IME composition fails. This first screenshot renders a dropdown with inputValue controlled. I clicked the input to focus it and then typed "j" + "a". Screen Shot 2022-12-09 at 11 45 05 AM

    What happened: The IME editor failed to open to further compose the characters before committing them. What I should have saw would have been this: Screen Shot 2022-12-09 at 11 45 50 AM Additionally, it appears that the compositionend event is never fired when inputValue is controlled.

    Problem description: When useCombobox is controlling inputValue and updating it with onInputValueChange, IME composition exits before showing the composition editor.

    Suggested solution: Wrap getInputProps's onChange handler with the spirit of the following:

      const onComposition = useRef(false);
      const getOnChangeWithCompositionSupport = useCallback(
        ({
            onChangeProp,
          }: {
            onChangeProp: (e: ChangeEvent<HTMLInputElement>) => void;
          }) =>
          (event: ChangeEvent<HTMLInputElement>) => {
            setInputValue(event?.target?.value);
    
            // IME method start
            if (event.type === 'compositionstart') {
              onComposition.current = true;
              return;
            }
    
            // IME method end
            if (event.type === 'compositionend') {
              onComposition.current = false;
            }
    
            // handle parent onChange
            if (!onComposition.current) {
              onChangeProp?.(event);
            }
          },
        [setInputValue]
      );
    
    bug 
    opened by blovato 1
  • Make Selects built with `useMultipleSelection` work with traditional forms

    Make Selects built with `useMultipleSelection` work with traditional forms

    Hey,

    I was wondering how to use useMultipleSelection to create a Multi-Select/Multi-Combobox that can be used to handle submit/change events of traditional forms (i.e. a way to create suitable name/value entries). I know that for a Single-Combobox, we can pass a name to getInputProps which works just fine.

    <input  {...getInputProps({ name })} />
    

    If we're doing the same for a multi-select, that of course does not work since there is more than just one value. We're currently rendering a hidden native <select> and set the options' selected attributes according to our current state, then dispatching a change event programmatically so that we can do something like

    <form onChange={handleChange}>
      <OurMultiselect values={/*...*/} />
    </form>
    

    Doing so feels unnecessary and we're probably just missing something that's built-in to downshift.

    In other words: We'd like our custom Multi-Select to behave just like its native counterpart without having to write custom code that enables this behavior. Is there an option we're missing or is this supposed to be solved in user-land?

    const handleChange= (event) => {
      const formData = new FormData(event.currentTarget);
      console.log([...formData.entries()]);
    };
    
    <form onChange={handleChange}>
      <select multiple name="native-select">
        <option value="a">A</option>
        <option value="b">B</option>
      </select>
    </form>
    

    Thank you

    • downshift version: 7.0.4
    • node version: 16.17.0
    • npm version: 8.15.0
    enhancement 
    opened by hollandThomas 1
  • Radix ui with downshift select

    Radix ui with downshift select

    • downshift version: 7.0.1
    • node version: 19.1.0
    • npm (or yarn) version: npm

    Relevant code or config

        <Popover.Root
        onOpenChange={() => {
          openMenu();
        }}
        >
          <Popover.Trigger asChild>
            <button>
              <div
                /* ref={getToggleButtonProps().ref} */
              >
                <span>{selectedItem ? selectedItem.title : "Elements"}</span>
                <span>{isOpen ? <>&#8593;</> : <>&#8595;</>}</span>
              </div>
            </button>
          </Popover.Trigger>
            {isOpen && (
              <Popover.Portal forceMount>
                <Popover.Content
                  asChild
                  className="z-10 w-72 h-[300px] max-h-80 overflow-scroll"
                >
                  <motion.div initial={{opacity: 0, y: 10, skewX: "5deg"}} animate={{opacity: 1, y: 0, skewX: "0deg"}}>
                    <ul className="bg-white" {...getMenuProps()}>
                      {books.map((item: any, index) => (
                        <li
                          className={cn(
                            highlightedIndex === index && "bg-blue-300",
                            selectedItem === item && "font-bold",
                            "py-2 px-3 shadow-sm flex flex-col"
                          )}
                          key={`${item.value}${index}`}
                          {...getItemProps({ item, index })}
                        >
                          <span>{item.title}</span>
                          <span className="text-sm text-gray-700">
                            {item.author}
                          </span>
                        </li>
                      ))}
                    </ul>
                  </motion.div>
                </Popover.Content>
              </Popover.Portal>
            )}
        </Popover.Root>
    
    

    What you did: trying to use Radix ui Popover with downshift select

    What happened: I get these errors in the console

    downshift.esm.js:1844 downshift: The ref prop "ref" from getToggleButtonProps was not applied correctly on your element.

    and

    downshift.esm.js:1844 downshift: The ref prop "ref" from getMenuProps was not applied correctly on your element.

    question 
    opened by abdallahz3 1
  • Callbacks called twice

    Callbacks called twice

    • downshift version: Tested with 6.1.12, 7.0.1 and d62ba91e3fd5f2fc3b0fa33f7497e5f78fa3c572
    • node version: 16.18.1
    • pnpm version: 7.15.0
    • react version: 18.2.0

    What you did:

    We are using the useSelect hook to display a custom dropdown on larger viewpoints and a modal on smaller viewports. We recently upgraded to React 18.

    What happened:

    Under certain conditions, the onSelectedItemChange callback is called twice when selecting an item.

    Reproduction repository:

    Unfortunately, I am unable to provide a reproduction repo at this point.

    Problem description:

    The problem started to appear when we updated to React 18. We did some debugging and found that the dispatch function of downshift's reducer is only called once, however, the actual reducer function is called twice under certain circumstances.

    According to the React Docs and this issue, reducers should be written in such a way, that them being called twice has no observable effects for the rest of the application.

    However, in downshift's case, the state is updated twice with two distinct objects, each containing the exact same information. This leads to the useEffect being called twice and thus triggering the callback twice.

    Suggested solution:

    I don't think that we should try to fix the reducer being called twice, due to the lack of a reproduction repo and the fact that React tells developers to expect such behaviour.

    Instead, I'd suggest to modify the reducer in such a way, that it being executed twice won't have any observable side effects. A possible solution might be to replace the following identity check with a deepEqual: https://github.com/downshift-js/downshift/blob/7540e3d925ea9eeddf9fe3780b5b4117563e1b1c/src/hooks/utils.js#L182 I.e.:

        if (action && prevStateRef.current && !deepEqual(prevStateRef.current, state)) {
    

    with deepEqual being something like this: https://stackoverflow.com/a/32922084

    However, I am not sure if this approach has any unintended consequences.

    question needs investigation 
    opened by thosta-Witt-Gruppe 2
Releases(v7.1.0)
Owner
Downshift
Home of the downshift project
Downshift
A set of React components implementing Google's Material Design specification with the power of CSS Modules

React Toolbox is a set of React components that implement Google's Material Design specification. It's powered by CSS Modules and harmoniously integra

React Toolbox 8.7k Dec 30, 2022
A React utility belt for function components and higher-order components.

A Note from the Author (acdlite, Oct 25 2018): Hi! I created Recompose about three years ago. About a year after that, I joined the React team. Today,

Andrew Clark 14.8k Jan 4, 2023
Nextjs-components: A collection of React components

nextjs-components A collection of React components, transcribed from https://vercel.com/design. 1 Motivation Blog post from 01/09/2022 Todo's Unit tes

null 94 Nov 30, 2022
Shows how React components and Redux to build a friendly user experience with instant visual updates and scaleable code in ecommerce applications

This simple shopping cart prototype shows how React components and Redux can be used to build a friendly user experience with instant visual updates and scaleable code in ecommerce applications.

Alan Vieyra 4 Feb 1, 2022
An accessible dropdown component for use in Ember apps.

ember-a11y-dropdown This is an accessible dropdown that you can use in your Ember app for a menu dropdown. I'm making it so people can stop using the

Melanie Sumner 2 Feb 10, 2022
A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable listโœŒ๏ธ

A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list Examples available here: http://claude

Claudรฉric Demers 10.3k Jan 2, 2023
nivo provides a rich set of dataviz components, built on top of the awesome d3 and Reactjs libraries

nivo provides supercharged React components to easily build dataviz apps, it's built on top of d3. Several libraries already exist for React d3 integr

Raphaรซl Benitte 10.9k Dec 31, 2022
Vue-hero-icons - A set of free MIT-licensed high-quality SVG icons, sourced from @tailwindlabs/heroicons, as Vue 2 functional components.

vue-hero-icons For Vue3, install the official package @heroicons/vue A set of free MIT-licensed high-quality SVG icons, sourced from @tailwindlabs/her

Mathieu Schimmerling 97 Dec 16, 2022
Minimal Design, a set of components for Angular 9+

Alyle UI Minimal Design, a set of components for Angular. Docs Install Alyle UI Installation Components Feature State Responsive Docs avatar โœ”๏ธ โœ”๏ธ Doc

Alyle 281 Dec 25, 2022
The Power CAT code components are a set of Power Apps component framework (PCF) controls that can be used to enhance power apps.

Power CAT code components The Power CAT code components are a set of Power Apps component framework (PCF) controls that can be used to enhance power a

Microsoft 70 Jan 2, 2023
The Select Component for React.js

React-Select The Select control for React. Initially built for use in KeystoneJS. See react-select.com for live demos and comprehensive docs. React Se

Jed Watson 25.6k Jan 3, 2023
Set of property utilities for Stitches with theme tokens support. Use the built-in utils, or easily build custom ones.

Stitches Mix Set of property utilities for Stitches with theme tokens support. Use the built-in utils, or easily build custom ones. Usage To import al

Joรฃo Pedro Schmitz 12 Aug 8, 2022
React components and hooks for creating VR/AR applications with @react-three/fiber

@react-three/xr React components and hooks for creating VR/AR applications with @react-three/fiber npm install @react-three/xr These demos are real,

Poimandres 1.4k Jan 4, 2023
A react component available on npm to easily link to your project on github and is made using React, TypeScript and styled-components.

fork-me-corner fork-me-corner is a react component available on npm to easily link to your project on github and is made using React, TypeScript and s

Victor Dantas 9 Jun 30, 2022
we are make our components in story book. So if we add some components you can find document and example of useage in storybook.

we are make our components in story book. So if we add some components you can find document and example of useage in storybook.

๊ณ ์Šค๋ฝ 6 Aug 12, 2022
Providing accessible components with Web Components & Material You

tiny-material Still on developing, DO NOT use for production environment Run well on Google Chrome, Firefox, Chrome for Android, Microsoft Edge (Chrom

HugePancake 11 Dec 31, 2022
A declarative, efficient, and flexible JavaScript library for building user interfaces.

React ยท React is a JavaScript library for building user interfaces. Declarative: React makes it painless to create interactive UIs. Design simple view

Facebook 200.2k Jan 8, 2023
๐ŸŒŠ A flexible and fun JavaScript file upload library

A JavaScript library that can upload anything you throw at it, optimizes images for faster uploads, and offers a great, accessible, silky smooth user

pqina 13.1k Dec 31, 2022
A very lightweight and flexible accessible modal dialog script.

A11y Dialog This is a lightweight (1.3Kb) yet flexible script to create accessible dialog windows. Documentation โ†— Demo on CodeSandbox โ†— Features: Clo

Kitty Giraudel 2.1k Jan 2, 2023