npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-select

v0.0.6

Published

⚛️ A react hook for building enhanced input components

Downloads

1,183

Readme

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.

| Option | Required | Type | Description | | -------------- | -------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | multi | | Boolean | When true, multi-select mode is used | | create | | Boolean | When true, create mode is used. | | duplicates | | Boolean | When true, allows options with duplicate values to be selected in multi-mode | | options | true | Array[{value, lable}) | An array of option objects. Each object should contain a value and label property | | value | true | any || Array[any] | The current value, or array of values if using multi mode | | onChange | true | Function(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 | | scrollToIndex | | Function(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. | | shiftAmount | | Number | The amount of options to navigate when using the keyboard to navigate with the shift key. Defaults to 5 | | filterFn | | Function(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 | | getCreateLabel | | Function(searchValue) => String | A custom function can be used here to format and return the label that is used to create new values in create mode | | optionsRef | true | React.createRef() or useRef() instance | This 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. | | stateReducer | | Function(oldState, newState, action) => state | A 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:

| Property | Type | Description | | ----------------- | ---------------------------------- | ----------- | | State | | | | visibleOptions | Array | -- | | selectedOption | Option | -- | | highlightedOption | Option | -- | | searchValue | String | -- | | isOpen | Bool | -- | | Actions | | | | highlightIndex | Function(Int) | -- | | selectOption | Function(Option) | -- | | removeValue | Function(Int) | -- | | setOpen | Function(Bool) | -- | | setSearch | Function(String) | -- | | Prop Getters | | | | getInputProps | Function(userProps) => inputProps | -- | | getOptionProps | Function(userProps) => optionProps | -- | | Other | | | | optionsRef | React 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!