downshift README

The project's README from github.com/downshift-js/downshift. As one markdown file: README.md.

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][build-badge]][build] [![Code Coverage][coverage-badge]][coverage] [![downloads][downloads-badge]][npmcharts] [![version][version-badge]][package] [![MIT License][license-badge]][license]

All Contributors [![PRs Welcome][prs-badge]][prs] [![Chat][chat-badge]][chat] [![Code of Conduct][coc-badge]][coc] [![Join the community on Spectrum][spectrum-badge]][spectrum]

[![Supports React and Preact][react-badge]][react] [![size][size-badge]][unpkg-dist] [![gzip size][gzip-badge]][unpkg-dist] [![module formats: umd, cjs, and es][module-formats-badge]][unpkg-dist]

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][aria] design pattern for a [combobox][combobox-aria-example] or a [select][select-aria-example], 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.

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][migration-guide-v7] 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][hooks-readme] 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][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][use-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][npm] which is bundled with [node][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][code-sandbox-try-it-out]

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][code-sandbox-no-get-root-props].

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!"][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).

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.

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

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.

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.

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 (downshift-js/downshift)

Searching Database…

12.3K ·GitHub
Что это такое?Набор строительных блоков (примитивов), чтобы делать в React свои собственные компоненты автодополнения, комбинированных списков, выпадающих списков выбора или мультивыбора с тегами — со встроенной доступностью по стандарту WAI-ARIA.
Это библиотека готовых стилизованных виджетов или решение более низкого уровня?Более низкого уровня: она headless, то есть без какой-либо внешней графики. Хуки плюс один компонент с render-prop берут на себя состояние, работу с клавиатурой и ARIA-семантику, а всю часть интерфейса — разметку и стили — вы делаете и оформляете сами.
Как добавить её в проект?Установите пакет из npm как зависимость приложения (npm install downshift) вместе с react, затем начните с хука useSelect или useCombobox; примеры на CodeSandbox и полная документация есть по ссылкам в README.
Обязательно ли использовать React, чтобы работать с ней?React обязателен — сам пакет от него зависит. Preact тоже работает из коробки: импортируйте Downshift from 'downshift/preact'.
Если я использую старый компонент Downshift вместо хуков, о чём стоит помнить?О двух вещах: во-первых, он не поддерживает новейшие паттерны W3C ARIA для комбинированных списков, и его полностью удалят, когда хуки дозреют; во-вторых, разметка, собранная без getRootProps, не полностью доступна для скринридеров.
Нужно ли глубоко разбираться в доступности, чтобы пользоваться ею правильно?Нет. Любой React-разработчик освоит её: downshift сам управляет ARIA-семантикой и объявлениями для скринридеров, с разумными сообщениями по умолчанию, которые можно переопределить.
С чего начать — с хуков или с компонента Downshift?Начните с хуков: useSelect, useCombobox и useTagGroup следуют паттерну комбинированного списка ARIA 1.2 (начиная с v7) и активно поддерживаются. Старый компонент с render-prop вдохновил их на создание и будет удалён, когда хуки окончательно дозреют.
Насколько сильно я могу управлять его внутренним поведением?Очень сильно. Проп stateReducer срабатывает при каждом внутреннем изменении состояния: вы получаете текущее состояние вместе с ожидающими изменениями и возвращаете те из них, которые нужны — тонкая настройка без полностью контролируемых пропов.
Могут ли мои варианты быть объектами, а не простыми строками?Да, подойдёт любая структура. Передайте itemToString, чтобы указать, какую строку брать для значения поля ввода; эта функция также вызывается с null, когда пользователь бросает ввод, поэтому добавьте в неё проверку на null.
Работает ли он с React Native?Да. В README есть раздел про React Native, а при сборке пакета создаются отдельные сборки для React Native, так что те же примитивы подходят и для элементов управления в нативных приложениях.
Size
2.6 MB
Stars
12.3K
Age
9y
Commits · 90 Days