0.0.6 • Published 4 years ago

use-select v0.0.6

Weekly downloads
579
License
MIT
Repository
github
Last release
4 years ago

use-select

⚛️ Hooks for building enhanced input components in React

Features

  • Headless
  • Multi-Select
  • Taggable
  • Extensible
  • 4kb gzipped

Demo

Installation

yarn add use-select
# or
npm i -s use-select

Basic Usage

import React, { useRef } from 'react'
import useSelect from 'use-select'

// Create your select component
function MySelect({
  value,
  options,
  onChange,
  multi,
  pageSize = 10,
  itemHeight = 40
}) {
  // Create a ref for the options container
  const optionsRef = useRef()

  // Use useSelect to manage select state
  const {
    visibleOptions,
    selectedOption,
    highlightedOption,
    getInputProps,
    getOptionProps,
    isOpen
  } = useSelect({
    multi,
    options,
    value,
    onChange,
    optionsRef
  })

  // Build your select component
  return (
    <div>
      {multi ? (
        <div>
          {selectedOption.map(option => (
            <div key={option.value}>
              {option.value}{' '}
              <span
                onClick={() => onChange(value.filter(d => d !== option.value))}
              >
                x
              </span>
            </div>
          ))}
        </div>
      ) : null}
      <input {...getInputProps()} placeholder="Select one..." />
      <div>
        {isOpen ? (
          <div ref={optionsRef}>
            {!visibleOptions.length ? (
              <div>No options were found...</div>
            ) : null}
            {visibleOptions.map(option => {
              return (
                <div
                  {...getOptionProps({
                    option,
                    style: {
                      background: `${props =>
                        highlightedOption === option
                          ? 'lightblue'
                          : selectedOption === option
                          ? 'lightgray'
                          : 'white'}`
                    }
                  })}
                >
                  {option.label}
                </div>
              )
            })}
          </div>
        ) : null}
      </div>
    </div>
  )
}

Documentation

Options

useSelect accepts a single object of options. Some options are required.

OptionRequiredTypeDescription
multiBooleanWhen true, multi-select mode is used
createBooleanWhen true, create mode is used.
duplicatesBooleanWhen true, allows options with duplicate values to be selected in multi-mode
optionstrueArray[{value, lable})An array of option objects. Each object should contain a value and label property
valuetrueany || Array[any]The current value, or array of values if using multi mode
onChangetrueFunction(value)The function that will be called with the new value(s) when the select is updated. This function will be passed a single value eg. onChange(newValue) when using single mode, or an array of values, with the newly added value as the second parameter eg. onChange([...values], newValue) when using multi mode
scrollToIndexFunction(optionIndex)A function that is called when the highlighted option index changes and should be scroll to. This is useful for custom windowing libraries like react-window or react-virtualized.
shiftAmountNumberThe amount of options to navigate when using the keyboard to navigate with the shift key. Defaults to 5
filterFnFunction(options, searchValue) => Options[]A custom function can be used here to filter and rank/sort the options based on the search value. It is passed the options array and the current searchValue and should return the filtered and sorted array of options to be displayed. By default a basic filter/sort function is provided. This function compares lowercase versions of the labels and searchValue using String.contains() and String.indexOf() to filter and sort the options. For a more robust ranking, we recommend using match-sorter
getCreateLabelFunction(searchValue) => StringA custom function can be used here to format and return the label that is used to create new values in create mode
optionsReftrueReact.createRef() or useRef() instanceThis ref is used to track outside clicks that close the options panel. Though not strictly required, it is highly recommended. You are then required to place this ref on the React element or compoenent that renders your options.
stateReducerFunction(oldState, newState, action) => stateA function that can be used to reduce the internal state of hook. Action types are available at useSelect.actions

Api

useSelect returns an object of values and functions that you can use to build your select component:

PropertyTypeDescription
State
visibleOptionsArray--
selectedOptionOption--
highlightedOptionOption--
searchValueString--
isOpenBool--
Actions
highlightIndexFunction(Int)--
selectOptionFunction(Option)--
removeValueFunction(Int)--
setOpenFunction(Bool)--
setSearchFunction(String)--
Prop Getters
getInputPropsFunction(userProps) => inputProps--
getOptionPropsFunction(userProps) => optionProps--
Other
optionsRefReact Ref--

Custom Windowing and Styles

useSelect is built as a headless hook so as to allow you to render and style your select component however you'd like. This codesandbox example shows a simple example of using react-window and styled-components to do that.

How was use-select built?!

Watch this two-part series on how I built it from the ground up using React hooks!

Contribution and Roadmap

  • Improve Accessibility (Hopefully to the level of Downshift)
  • Write Tests
  • Continuous Integration & Automated Releases

Open an issue or PR to discuss!

Inspiration and Thanks

This library was heavily inspired by Downshift. Thank you to all of its contributors!

0.0.6

4 years ago

0.0.5

4 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago