GithubHelp home page GithubHelp logo

downshift-js / downshift Goto Github PK

View Code? Open in Web Editor NEW
12.0K 81.0 932.0 2.59 MB

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

Home Page: http://downshift-js.com/

License: MIT License

JavaScript 97.59% TypeScript 2.41%
react autocomplete combobox autoselect select autosuggest multiselect dropdown accessible wai-aria

downshift's Introduction

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.

Both useSelect and useCombobox support the latest ARIA combobox patterns for W3C, which Downshift does not. Consequently, we strongly recommend the you use the hooks. The hooks have been migrated to the ARIA 1.2 combobox pattern in the version 7 of downshift. There is a Migration Guide that documents the changes introduced in version 7.

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!

🚨 Use the Downshift hooks 🚨

If you are new to the library, consider the useSelect and useCombobox hooks as the first option. As mentioned above, the hooks benefit from the updated ARIA patterns and are actively maintained and improved. If there are use cases that are supported by the Downshift component and not by the hooks, please create an issue in our repo. The Downshift component is going to be removed completely once the hooks become mature.

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.keyDownHome
  • Downshift.stateChangeTypes.keyDownEnd
  • Downshift.stateChangeTypes.clickItem
  • Downshift.stateChangeTypes.blurInput
  • Downshift.stateChangeTypes.changeInput
  • Downshift.stateChangeTypes.keyDownSpaceButton
  • Downshift.stateChangeTypes.clickButton
  • Downshift.stateChangeTypes.blurButton
  • Downshift.stateChangeTypes.controlledPropUpdatedSelectedItem
  • Downshift.stateChangeTypes.touchEnd

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

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

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.

This is unnecessary if you are using React 18 or newer

You should never need to use this in the browser. Only if you are running 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
Kent C. Dodds

πŸ’» πŸ“– πŸš‡ ⚠️ πŸ‘€ πŸ“ πŸ› πŸ’‘ πŸ€” πŸ“’
Ryan Florence
Ryan Florence

πŸ€”
Jared Forsyth
Jared Forsyth

πŸ€” πŸ“–
Jack Moore
Jack Moore

πŸ’‘
Travis Arnold
Travis Arnold

πŸ’» πŸ“–
Marcy Sutton
Marcy Sutton

πŸ› πŸ€”
Jeremy Gayed
Jeremy Gayed

πŸ’‘
Haroen Viaene
Haroen Viaene

πŸ’‘
monssef
monssef

πŸ’‘
Federico Zivolo
Federico Zivolo

πŸ“–
Divyendu Singh
Divyendu Singh

πŸ’‘ πŸ’» πŸ“– ⚠️
Muhammad Salman
Muhammad Salman

πŸ’»
JoΓ£o Alberto
JoΓ£o Alberto

πŸ’»
Bernard Lin
Bernard Lin

πŸ’» πŸ“–
Geoff Davis
Geoff Davis

πŸ’‘
Anup
Anup

πŸ“–
Ferdinand Salis
Ferdinand Salis

πŸ› πŸ’»
Kye Hohenberger
Kye Hohenberger

πŸ›
Julien Goux
Julien Goux

πŸ› πŸ’» ⚠️
Joachim Seminck
Joachim Seminck

πŸ’»
Jesse Harlin
Jesse Harlin

πŸ› πŸ’‘
Matt Parrish
Matt Parrish

πŸ”§ πŸ‘€
thom
thom

πŸ’»
Vu Tran
Vu Tran

πŸ’»
Codie Mullins
Codie Mullins

πŸ’» πŸ’‘
Mohammad Rajabifard
Mohammad Rajabifard

πŸ“– πŸ€”
Frank Tan
Frank Tan

πŸ’»
Kier Borromeo
Kier Borromeo

πŸ’‘
Paul Veevers
Paul Veevers

πŸ’»
Ron Cruz
Ron Cruz

πŸ“–
Rick McGavin
Rick McGavin

πŸ“–
Jelle Versele
Jelle Versele

πŸ’‘
Brent Ertz
Brent Ertz

πŸ€”
Justice Mba
Justice Mba

πŸ’» πŸ“– πŸ€”
Mark Ellis
Mark Ellis

πŸ€”
us͑an̸df͘rien͜ds͠
us͑an̸df͘rien͜ds͠

πŸ› πŸ’» ⚠️
Robin Drexler
Robin Drexler

πŸ› πŸ’»
Arturo Romero
Arturo Romero

πŸ’‘
yp
yp

πŸ› πŸ’» ⚠️
Dave Garwacke
Dave Garwacke

πŸ“–
Ivan Pazhitnykh
Ivan Pazhitnykh

πŸ’» ⚠️
Luis Merino
Luis Merino

πŸ“–
Andrew Hansen
Andrew Hansen

πŸ’» ⚠️ πŸ€”
John Whiles
John Whiles

πŸ’»
Justin Hall
Justin Hall

πŸš‡
Pete NykΓ€nen
Pete NykΓ€nen

πŸ‘€
Jared Palmer
Jared Palmer

πŸ’»
Philip Young
Philip Young

πŸ’» ⚠️ πŸ€”
Alexander Nanberg
Alexander Nanberg

πŸ“– πŸ’»
Pete Redmond
Pete Redmond

πŸ›
Nick Lavin
Nick Lavin

πŸ› πŸ’» ⚠️
James Long
James Long

πŸ› πŸ’»
Michael Ball
Michael Ball

πŸ› πŸ’» ⚠️
CAVALEIRO Julien
CAVALEIRO Julien

πŸ’‘
Kim GrΓΆnqvist
Kim GrΓΆnqvist

πŸ’» ⚠️
Sijie
Sijie

πŸ› πŸ’»
Dony Sukardi
Dony Sukardi

πŸ’‘ πŸ’¬ πŸ’» ⚠️
Dillon Mulroy
Dillon Mulroy

πŸ“–
Curtis Tate Wilkinson
Curtis Tate Wilkinson

πŸ’»
Brice BERNARD
Brice BERNARD

πŸ› πŸ’»
Tony Xu
Tony Xu

πŸ’»
Anthony Ng
Anthony Ng

πŸ“–
S S
S S

πŸ’¬ πŸ’» πŸ“– πŸ€” ⚠️
Austin Tackaberry
Austin Tackaberry

πŸ’¬ πŸ’» πŸ“– πŸ› πŸ’‘ πŸ€” πŸ‘€ ⚠️
Jean Duthon
Jean Duthon

πŸ› πŸ’»
Anton Telesh
Anton Telesh

πŸ› πŸ’»
Eric Edem
Eric Edem

πŸ’» πŸ“– πŸ€” ⚠️
Austin Wood
Austin Wood

πŸ’¬ πŸ“– πŸ‘€
Mark Murray
Mark Murray

πŸš‡
Gianmarco
Gianmarco

πŸ› πŸ’»
Emmanuel Pastor
Emmanuel Pastor

πŸ’‘
dalehurwitz
dalehurwitz

πŸ’»
Bogdan Lobor
Bogdan Lobor

πŸ› πŸ’»
Luke Herrington
Luke Herrington

πŸ’‘
Brandon Clemons
Brandon Clemons

πŸ’»
Kieran
Kieran

πŸ’»
Brushedoctopus
Brushedoctopus

πŸ› πŸ’»
Cameron Edwards
Cameron Edwards

πŸ’» ⚠️
stereobooster
stereobooster

πŸ’» ⚠️
Trevor Pierce
Trevor Pierce

πŸ‘€
Xuefei Li
Xuefei Li

πŸ’»
Alfred Ringstad
Alfred Ringstad

πŸ’»
D[oa]vid Weisz
D[oa]vid Weisz

πŸ’»
Royston Shufflebotham
Royston Shufflebotham

πŸ› πŸ’»
MichaΓ«l De Boey
MichaΓ«l De Boey

πŸ’»
Henry
Henry

πŸ’»
Andrew Walton
Andrew Walton

πŸ› πŸ’» ⚠️
Arthur Denner
Arthur Denner

πŸ’»
Cody Olsen
Cody Olsen

πŸ’»
Thomas Ladd
Thomas Ladd

πŸ’»
lixualinta
lixualinta

πŸ’»
Jacob Cofman
Jacob Cofman

πŸ’»
Joshua Freedman
Joshua Freedman

πŸ’»
Amy
Amy

πŸ’‘
Rogin Farrer
Rogin Farrer

πŸ’»
Dmitrii Kanatnikov
Dmitrii Kanatnikov

πŸ’»
Dallon Feldner
Dallon Feldner

πŸ› πŸ’»
Samuel Fuller Thomas
Samuel Fuller Thomas

πŸ’»
Ryan Castner
Ryan Castner

πŸ’»
Silviu Alexandru Avram
Silviu Alexandru Avram

πŸ› πŸ’» ⚠️
Anton Volkov
Anton Volkov

πŸ’» ⚠️
Keegan Street
Keegan Street

πŸ› πŸ’»
Manuel DuguΓ©
Manuel DuguΓ©

πŸ’»
Max Karadeniz
Max Karadeniz

πŸ’»
Gonzalo Beviglia
Gonzalo Beviglia

πŸ› πŸ’» πŸ‘€
Brian Kilrain
Brian Kilrain

πŸ› πŸ’» ⚠️ πŸ“–
Gerd Zschaler
Gerd Zschaler

πŸ’» πŸ›
Karen Gasparyan
Karen Gasparyan

πŸ’»
Sergey Korchinskiy
Sergey Korchinskiy

πŸ› πŸ’» ⚠️
Edygar Oliveira
Edygar Oliveira

πŸ’» πŸ›
epeicher
epeicher

πŸ›
François Chalifour
François Chalifour

πŸ’» ⚠️ πŸ“¦
Maxim Malov
Maxim Malov

πŸ› πŸ’»
Enrique Piqueras
Enrique Piqueras

πŸ€”
Oleksandr Fediashov
Oleksandr Fediashov

πŸ’» πŸš‡ πŸ€”
Mikhail Bashurov
Mikhail Bashurov

πŸ’» πŸ›
Joshua Godi
Joshua Godi

πŸ’»
Kanitkorn Sujautra
Kanitkorn Sujautra

πŸ› πŸ’»
Jorge Moya
Jorge Moya

πŸ’» πŸ›
Jakub JastrzΔ™bski
Jakub JastrzΔ™bski

πŸ’»
Shukhrat Mukimov
Shukhrat Mukimov

πŸ’»
Jhonny Moreira
Jhonny Moreira

πŸ’»
stefanprobst
stefanprobst

πŸ’» ⚠️
Louisa Spicer
Louisa Spicer

πŸ’» πŸ›
Ryō Igarashi
Ryō Igarashi

πŸ› πŸ’»
Ryan Lue
Ryan Lue

πŸ“–
Mateusz Leonowicz
Mateusz Leonowicz

πŸ’»
Dennis Thompson
Dennis Thompson

⚠️
Maksym Boytsov
Maksym Boytsov

πŸ’»
Sergey Skrynnikov
Sergey Skrynnikov

πŸ’» ⚠️
Vincent Voyer
Vincent Voyer

πŸ“–
limejoe
limejoe

πŸ’» πŸ›
Manish Kumar
Manish Kumar

πŸ’»
Anang Fachreza
Anang Fachreza

πŸ“– πŸ’‘
Nick Deom
Nick Deom

πŸ’» πŸ›
ClΓ©ment Garbay
ClΓ©ment Garbay

πŸ’»
Kaimin Huang
Kaimin Huang

πŸ’» πŸ›
David Welling
David Welling

πŸ’» πŸ› πŸ€” πŸ”¬
chandrasekhar1996
chandrasekhar1996

πŸ› πŸ’»
Brendan Drew
Brendan Drew

πŸ’»
Jean Pan
Jean Pan

πŸ’»
Tom Jenkinson
Tom Jenkinson

πŸš‡
Alice Hendicott
Alice Hendicott

πŸ’» πŸ›
Zach Davis
Zach Davis

πŸ’» πŸ›

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

LICENSE

MIT

downshift's People

Contributors

alexandernanberg avatar allcontributors[bot] avatar amollusk avatar andarist avatar austintackaberry avatar cloud-walker avatar codiemullins avatar donysukardi avatar eliperkins avatar ferdinandsalis avatar franklixuefei avatar iwalkalone avatar johnjesse avatar jorgemoya avatar l-i-x-u avatar mufasa71 avatar oliviertassinari avatar pbomb avatar rendez avatar rezof avatar robin-drexler avatar samuelfullerthomas avatar silviuaavram avatar souporserious avatar tansongyang avatar thomhos avatar tladd avatar trysound avatar vutran avatar yp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

downshift's Issues

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! πŸ‘‹ now that we've released a beta version, it's much easier to make examples. Now you can make them right in the browser πŸŽ‰ (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 πŸ‘‹

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!

Use refs for items in place of data-attributes

Now that we have a way to do this for the root element, how do you feel about taking the same approach for items and allow them to accept a refKey? I imagine there is a small perf win here since we would have access to the node and not have to query it.

should 0 index mean no selection?

I'm not sure the official ARIA guidelines here. But should the arrow navigation act in a way where you can always get back to just the text you have entered like in the following gif:

autocomplete

You can test it here. It looks like Google and Facebook searches behave this way as well.

If there is no scrollable node it results in an error

  • react-kadabra version: 1.0.0-beta.7
  • node version: 8.1.4
  • npm (or yarn) version: 5.3.0

What I did:
Clicked on the button that opens the list.

What happened:

Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
    at scrollIntoView (utils.js:70)
    at Autocomplete.maybeScrollToHighlightedElement (autocomplete.js:378)
    at Autocomplete.<anonymous> (autocomplete.js:84)

I tried to reproduce here but since codesandbox has a scrollable node at some point the error does not occur. However in local project I can reproduce. Setting the List Container to a maxHeight lower than the height of the contained elements 'fixes' the bug. If you need a repo of the actual behaviour let me know.

Problem description:
If there is no scrollable node it results in an error

Suggested solution:
I guess we should stop traversing the dom at the component boundary and if the scrollHeight equals clientHeight we do not need to scroll into view.

PS. I am love the flexibility the api provides. Great work!

Contribute to Tests

Hi Kent,

If I want to contribute to tests, what will be the best way to start? Have you considered what functionality should be covered first and move to the next i.e. priority list?

Discussion - Consider to move all example into separated projects

Currently, the examples are in 1 project. It is not flexible if we use many libs. For example, I saw some examples currently are using glamorous . What if I want to use styled-components or material-ui. So I suggest to consider to split examples to different projects.

Extend auto-selection options

As discussed in #9, explore expanding user options to tailor auto-selection of items to their needs.

Thoughts so far:

  • In cases were selection must be a listed item, auto-selection of best match seems appropriate.
  • In cases were input is not required to be listed item (e.g. creating a new item), auto-selection of a best match may be counter to intuitive behavior.
  • In cases where selection may or may not be a listed item, auto-selection of best match may be preferred, but functionality must exist to intuitively allow user to submit input as-is (no selection).
  • Some users type and submit/tab/enter too quickly to recognize that a selection has been automatically selected for them. In this case they will have to go back to the input and change the value, breaking flow.
  • Some users would like to use custom submit behavior to delineate selections (e.g. typing a , to delineate a new tag.

scrollIntoView throws error

scrollIntoView seems to be broken for just the Apollo example. I'll look into this today to see what is going on.

image

defaultValue can only be provided on initial render

  • downshift version: 1.0.0-beta.12
  • node version: 8.2.1
  • npm (or yarn) version: 5.3.0

Problem description:
When providing an initial value via defaultValue it will only be 'applied' on initial render. However when that value is only available at an later point (api call) it will be ignored.

Suggested solution:
Use component componentWillReceiveProps to handle the new defaultValue.

If this design is intended and my thinking is flawed feel free to close this issue. Though I would be happy for an explanation.

What can we remove?

I think we are getting to a point where we could move/remove things before 1.0.0. Ideas welcome. I think that we might be able to remove multiple with the new controlled/uncontrolled capabilities. We may be able to merge onChange and onStateChange... What else?

Flow typed

How do you feel about adding Flow to this project? Could even add inline comments while doing this so docs can be generated later.

We could even take it a step further and remove PropTypes in favor of just Flow with babel-plugin-react-flow-props-to-prop-types.

Add a11y attributes to the Input

Based on react-autocomplete in this example here's what the input renders:

<input id="states" role="combobox" aria-autocomplete="list" aria-expanded="true" autocomplete="off" value="">

We should probably add those to ours I think πŸ˜„

Should be pretty straightforward for anyone familiar with react.

Example, and question about api

  • downshift version: Beta
  • node version: 8.2.1
  • npm (or yarn) version: yarn 0.27.5

Relevant code or config

Hello! I've been fleshing out a super basic example that is for binding a list of object in the context of Material UI, that' I'd love to submit to the #1 when I've polished more.

image

see live example: https://codesandbox.io/s/QMGq4kAY

I had a question about the api, and its because I worked last night and also today, and I think I observed some of the values change. So quick questions:

  1. is it going to be value or inputValue
  2. is it going to be selectedItem or selectedValue
  3. also in the version that had selectedItem the function clearSelection seemed to clear both the input and the selected Item (which was convenient), and the new one only clears the selected selectedValue/selectedItem, is there another way to clear the input now? I get stuck with [object object

Thank ya'll for the awesome plugin, so far I really like it!!

Remove index prop from Item

I was messing around with sections to replace our current autocomplete and was finding the index prop to be tedious, and then I realized we might be able to get rid of it altogether. Is there any reason you can think of why we can't use indexOf? I added it locally and everything seems to be working πŸ‘Œ

selectItemAtIndex possible regression

  • Downshift: 1.0.0-beta-21
  • node version: 8.2.1
  • yarn 0.27.5

Relevant code or config

Before I explain the issue, heres the chunk of code to look for in the demo to be able to reproduce the issue. (around line 131 of the material-combobox.js file)

        const _props = getItemProps({
          value: item,
          index,
          "data-highlighted": highlightedIndex === index,
          "data-selected": selected,

          //This is the important event.
          onClick: () => {
            //selectItemAtIndex(index) //does not work
            selectItem(item); //works    
            //console.log('highlightedIndex', highlightedIndex)
            //selectHighlightedItem() //does not work.
          }
        });

Howdy! :) When I upgraded to 1.0.0-beta.21 from 1.0.0-beta.14, some issues such as the clearing of the autocomplete seem totally resolved and just about everything seems to be working well; however, I think two functions that are means to select items might have regressed (as they dont seem to work for me);

So I have a function that fires onClick. When I use the selectItem function, I can select the item directly, with no difficulty. However two functions, selectHighlightedItem, selectItemAtIndex might have regressed. looking at the code here: my first suspicion would be the selectItemAtIndex, since selectHighlightedItem (line 204) seems to depend on selectItemAtIndex (line 192);

Some important things to note:

  • I am logging every state change using the Handler onStateChange and I can see that as I hover over items, and type, the state is properly changing correctly.
  • I can also see the desired index is right when I am about to click, and am using the selectHighlightedItem, leading me to believe that it is probably fine itself.
  • You can reproduce the behavior by commenting and uncommenting the functions in that click handler
  • For me this also seems to affect the 'select on enter' that was working beforehand. This is unsurprising when I look here, (line 363) because the function calls selectHighlightedItem, which calls selectItemAtIndex

Its also possible I overlooked something obvious, and if I did, that won't surprise me at all :) I did my best to update this demo the right way, but if you think I made a mistake when I did, I appreciate the help.

Please let me know if I can add any more info :)

Name change

Pertaining to #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 - πŸ€·β€β™‚οΈ

Controlled vs uncontrolled

Right now this is totally uncontrolled (you can't pass the value in and can only get the value out). We should support controlled (passing the value in as well).

Someone brought up their use case to me in gitter and this is important I think.

Performance benchmark

Would be great to get an idea of the perf of this component and track that overtime or something. Also to find bottlenecks and speed them up.

Add smaller scroll-into-view

This is to keep track of what was discussed in this PR #15 (comment)

The current dom-scroll-into-view is a pretty heavy dependency. I ran into this same issue in one of my libs. I can PR a smaller version for now that should be a drop in replacement.

Accessibility feedback

Here are some things I found when I tested the component!

What Works

  • It works great from the keyboard. Very intuitive, and the clear results button is actionable. πŸ‘
  • Great job announcing the number of items available!

What Needs Work

  • The input needs a label, as placeholder isn't reliable in every assistive technology. You could use a unique aria-label, or ideally, a <label> element with text wrapping the input (which increases the hit area).
  • In Voiceover, you can't navigate with the arrow keys alone so the directions announcing "navigate with the up and down arrow keys" is inaccurate. You could try adding aria-activedescendant to the INPUT pointing to the ID of the currently highlighted item as you navigate. Here's a similar thread you could reference.
  • When an item is selected, the a11y-status-message says "no results" (see attached screenshot). It should say which item is selected. Same thing in NVDA and Voiceover.

Note: I can't even get codesandbox.io to load in IE, so I was unable to test it with JAWS.

no results when Anakin Solo is selected

Relying on the id attribute for selecting an item fails for compound components

  • downshift version: 1.0.0-beta.21
  • node version: 8.2.1
  • npm (or yarn) version: 5.3.0

What you did:
Render a compound component as Item.

What happened:
Item does not get selected.

Problem description:
Item get selected only when the target node has the id attribute. With compound components this is clearly a problem.

Suggested solution:
We could walk up the dom tree to the nearest id attribute (maybe use data-item-id) instead.

I think this problem was also mentioned in #110

Improve accessibility

I'm 99% sure that the current implementation enables users to be completely accessible, but I'd like to widen the pit of success here (by making it easier or, even better, automatic). We do this already with the MenuStatus component which is automatic and how easy it is to add aria- attributes to the things you render. Let's see if we can make it so people don't need to think about accessibility.

With the motivation out of the way, I'd like to use this issue to bring up opportunities to implement automatic accessibility or document recommendations/examples for this. Once we've decided that there's something we should do, we'll open an individual issue to track that specific thing and someone can work on implementing that.

RC release feedback

downshift version: 1.0.0-rc.1

Hello,

As I'm working on a material-ui / virtual-list example using downshift I have a little list of remaining issues :

  • The onMouseUp listener seems to force a rerender everytime we click outside of the component, even if there is no state / props changes. You can see the log on my codesandbox demo, try to click outside of the 2 components multiple times.
  • The selectedItem prop works great to make the component controlled, but the inputValue gets updated only when we finally click outside of the component (onMouseUp again I think). In my demo, try to select a value in the first component, then you'll notice the second one isn't updated fully until you click outside.
  • The scroll management done internally in the lib seems to be in conflict with windowing libraries. I suspect the scrollIntoView and other functions which need to access the items nodes to be the problem. As the list becomes virtual, it tries to scroll to them before they are rendered. I had to do weird tricks to make it somehow workable, like adding this to my input component :
onKeyDown: e => {
  if (
    !autocompleteProps.isOpen ||
    !["ArrowUp", "ArrowDown"].includes(e.key)
  ) {
    return;
  }
  const top =
    e.key === "ArrowUp" && autocompleteProps.highlightedIndex === 0;
  const bottom =
    e.key === "ArrowDown" &&
    autocompleteProps.highlightedIndex === filteredItems.length - 1;

  if (!top && !bottom) {
    return;
  }

  const scrollToIndex = top ? filteredItems.length - 1 : 0;

  // go to the top or bottom of the virtual-list
  scroll({
    scrollToIndex
  });

  // allows to wait that the node to be highlighted is mounted
  setTimeout(() => {
    autocompleteProps.setHighlightedIndex(scrollToIndex);
  }, 0);
}
  • The mouse interaction with the virtual-list is fine, but the keyboard one is buggy. When you hold ArrowUp or ArrowDown and the scroll gets too fast, the highlight / focus on item is lost.

  • Still virtual-list related, the Enter event listener seems to be active only on initial mounted nodes. When you try to hit ArrowUp, and go at the bottom of the list, you can't select an item hitting Enter.

Don't hesitate to play with my demo to verify all of these issues.

We are almost there, thanks a lot to all contributors for the great work! πŸ‘

Look into integrating Lerna

Pertaining to #1. I think it could be nice to have some lib supported packages that included components like Dropdown, or Select. @FezVrasta how did you like using Lerna in PopperJS? Do you think you could help here? I can take a stab at this if it seems worth it.

Can't unfocus on mobile

  • react-autocompletely version:
  • node version:
  • npm (or yarn) version:

Relevant code or config

https://codesandbox.io/s/9rWEmzEv8

What you did:

Open it on an iPhone, try to press "done", but it doesn't dismiss the focusing

What happened:

Input is permanently focused, not even the url bar is accessible. Can get the focus back out of it when pressing refresh only

Reproduction repository:

https://codesandbox.io/s/9rWEmzEv8

Problem description:

Suggested solution:

Allow the input to blur

A note on equlity testing

We should add a note somewhere about equality testing for props like isSelected. This will bite people (me just now ☺️) since objects might not be the 'same' across different render cycles. Maybe in the examples or in a notes section.

Windowing

One thing that could really help with performance is if we window the scrollable area for the autocomplete. I'm thinking that we could either just have an example of how to use this with react-virtualized or if it's not too complex, we could include our own miny implementation of windowing. Thoughts/ideas appreciated!

Add Label component

Related to #36: One thing that you want for a11y is a label for your input. Normally this is done by putting an id on the input and a for="the-id" on a label. So we could expose a Label component that automatically hooks up with the Input. That could be nice because it could generate a random ID to label the input. If the user provides an id prop to the Input, then we use that.

Should we invoke onStateChange with _all_ the state?

  • downshift version: 1.0.0-rc.3

Relevant code or config

class App extends React.Component {
  state = {inputValue: ''}
  handleStateChange = changes => {
    if (changes.hasOwnProperty('inputValue')) {
      this.setState({inputValue: changes.inputValue})
    }
  }
  render() {
    const {inputValue} = this.state
    return (
      <Div
        css={{
          display: 'flex',
          justifyContent: 'center',
          flexDirection: 'column',
          textAlign: 'center',
        }}
      >
        <h2>basic example</h2>
        <SemanticUIDownshift
          items={items}
          inputValue={inputValue}
          onStateChange={this.handleStateChange}
          onChange={() => {}}
          itemToString={i => (i ? i.name : '')}
          className={css({width: 250, margin: 'auto'})}
        />
      </Div>
    )
  }
}

Reproduction:

https://codesandbox.io/s/5yJ3G59jA

Problem description:

In my handleStateChange handler, I have to check whether inputValue is included in the changes if I want to set the state.

Suggested solution:

What if we just always pass all the state to your onStateChange callback? Then you wouldn't have to check whether inputValue (and other state) exists in the changes.

As I was creating this, I was thinking that maybe we should leave it as it is, because the alternative wouldn't enable you to know what changed, just that something changed.

But what if we did both? So it'd be: this.props.onStateChange(changes, allState)? I think that'd be a good compromise, so I'm going to do that πŸ˜„

Expose MenuStatus.getA11yStatusMessage

Right now the Menu component uses MenuStatus and doesn't pass getA11yStatusMessage. We should probably allow people to pass getA11yStatusMessage to Menu and have that forward to the rendered MenuStatus.

This should be quite simple for anyone used to React. Especially since we don't actually have any tests yet πŸ˜…

itemToString name change proposal

Are you tied to the name itemToString? After using react-autosuggest, I liked the prop name getSuggestionValue, seemed to be clear what it was. How would you feel about something like getItemValue or even more explicit getInputValue?

revert removal of blur handler

@kentcdodds after some testing on iOS, it turned out the blur handler removed at #46 is actually necessary.

Without this handler, dismissing the iOS keyboard (as shown in #32 (comment)) will not 'reset' the autocomplete controller, and therefore the menu will be left in the open state.

I would be able to implement my own blur handler if all the props of this.autocomplete were exposed (i.e. isMouseDown and reset()).

Preact compatibility

hey friends,

I've been trying to get this component to be compatible with preact by using a very thin compatibility layer instead of preact-compat module.

The final component renders fine in a pure preact project without compat but it hits a blocker on this line:

https://github.com/paypal/react-autocompletely/blob/master/src/menu.js#L132

would you be open to changing this single line from:

{children(this.autocomplete.getControllerStateAndHelpers())}

to something like:

React.Children.only(children)(  ..  )

if that's a possibility I think I should be able to complete the out of the box compat.

thanks!

Better isOpen control

I'm only on my phone so I haven't been able to test thoroughly, but since multiple logic has been removed, how should we handle keeping the menu open when selecting multiple values? I've actually wondered if this library should care about isOpen state the more I work with it. We use a Popover component at my work that takes care of this so I'm wondering if other people would face the same use case. I guess you could just ditch isOpen altogether and implement it yourself?

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 πŸ˜„

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

value of inputValue is undefined

  • downshift version: ^1.0.0-beta.8
  • node version: 6.5.0
  • yarn version: 0.21.3

Relevant code or config

function BasicAutocomplete({items, onChange}) {
  return (
    <Autocomplete onChange={onChange}>
      {({
        getInputProps,
        getItemProps,
        isOpen,
        inputValue,
        selectedValue,
        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({value: item, index})}
                    key={item}
                    style={{
                      backgroundColor:
                        highlightedIndex === index ? 'gray' : 'white',
                      fontWeight: selectedValue === item ? 'bold' : 'normal',
                    }}
                  >
                    {item}
                  </div>
                ))}
            </div>
          ) : null}
        </div>
      )}
    </Autocomplete>
  )
}

What you did:
I inputed keywork to filter result.

What happened:
inputValue is undefined

Suggested solution:
I replaced inputValue with value. It has worked fine. Just confuse value and inputValue

Implement react-autosuggest API

Anyone wanna take on this task? By doing this it would really help us know whether react-autocompletely is powerful enough to support these use cases and if there's anything we can do to improve the API.

What can we remove, need to add to getControllerStateAndHelpers?

The getControllerStateAndHelpers function currently exposes a bunch of things which we use to send to the users of the component. What should we add or remove from this?

State:

  • value
  • isOpen
  • selectedItem
  • highlightedIndex

Actions:

  • toggleMenu
  • openMenu - shortcut to toggleMenu(true), nice because you can pass it directly to an onClick={openMenu} rather than having to do: onClick={() => toggleMenu(true)}
  • closeMenu - shortcut to toggleMenu(false), nice for the same reasons as openMenu
  • selectItem
  • selectItemAtIndex - if we were to expose getItemFromIndex, then this could be a shortcut to selectItem(getItemFromIndex(index))
  • selectHighlightedItem - shortcut to selectItemAtIndex(highlightedIndex)
  • clearSelection
  • setHighlightedIndex

Prop getters:

  • getRootProps
  • getButtonProps
  • getInputProps
  • getItemProps

I think we should probably expose getItemFromIndex. What else should we expose? What should we hide? Is there a way to restructure/rename things?

Favor Array.prototype.filter() instead of Array.prototype.splice() when unmounting Item instances from the menu component

Problem description:

I've been following the streaming of the react-autocompletely and I've noticed some inconsistent behavior (on my re-implementation) when the Item components were unmounting, due to user interaction with the input element.

The removeItemInstance function on the Menu component, which uses Array.prototype.splice(), modifies the array in a non-deterministic way.

Suggested solution:

I propose on using Array.prototype.filter()

removeItemInstance(itemInstance) {
  const index = this.items.indexOf(itemInstance)
  if (index !== -1) {
    this.items = this.items.filter(function(item, itemIndex) {
      return itemIndex !== index;
    });
  }
}

Thank you! πŸ™ŒπŸ»

Edit: It seems that the problem is not with splice but with the way the Items are being rendered.

Make controlled component easier

  • downshift version: 1.0.0-beta.21

Hello all,

I find it still too hard to make the Autocomplete controlled.

The stateProps concept is great for edge cases, but I'd expect to have at least a value prop on Autocomplete so we can make it controlled without caring about the internal state.

I tried using the selectedItem but then I have to handle all other interactions to update it.

I think adding a value props is just a matter of checking if nextProps.value !== this.props.value in componentWillReceiveProps and then update the state accordingly?

The couple value + onChange props are pretty standard among inputs components, and defining a value prop is often what it takes to pass a component from uncontrolled to controlled.

What do you think?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.