Searchable, Async Dropdowns in React Using React-Select

Patrick Moriarty

React-Select is a highly configurable dropdown library for React that features dynamic search/filter, async option loading, accessibility, and fast render times.

In this post we'll cover React-Select 2, and at the time of this writing, React-Select v2 is still in beta release.

Setup

To install React-Select v2, add the react-select package with the @next tag using npm or yarn:

$ yarn add react-select@next

# or, using npm:
$ npm install react-select@next

After installation, the package is freely available to import as a React component.

import Select from 'react-select';

Usage

Despite its differences from HTML’s native <select> element, putting React-Select to use in your app is straightforward. At its simplest, we have a modern, searchable selection component:

React-Select Basic usage

The dropdown is searchable.

Search the dropdown

Produced by the following code:

import React from 'react';
import Select from 'react-select';

const scaryAnimals = [
  { label: "Alligators", value: 1 },
  { label: "Crocodiles", value: 2 },
  { label: "Sharks", value: 3 },
  { label: "Small crocodiles", value: 4 },
  { label: "Smallest crocodiles", value: 5 },
  { label: "Snakes", value: 6 },
];

const App = () => (
  <div className="app">
    <div className="container">
      <Select options={scaryAnimals} />
    </div>
  </div>
);

Not bad!

You’ll notice three things:

  • You must import the Select component from react-select.
  • Each object in the options array scaryAnimals must have at least two values: label, a string, and value, which may be any type.
  • The only required prop is the options array.

When using React-Select, I frequently find myself using Javascript’s map array method to prepare the options array:

someArrayOfStrings.map(opt => ({ label: opt, value: opt }));

To capture when the user selects an option, add the onChange prop:

<Select options={scaryAnimals}
  onChange={opt => console.log(opt.label, opt.value)} />

The value passed to the onChange function is the same object that makes up the option itself, so it will contain the value and label variables.

Other Features

Besides basic search and selection, React-Select offers other features like multi-select, user-creatable options, and async option loading.

Multi-select

To enable the multi-select, add the isMulti prop to your element:

Multi select

User-creatable options

To allow users to type a new option into the select component, we need to import the CreatableSelect component from react-select/lib/Creatable. Then, use it in a similar way you would the Select component:

<CreatableSelect options={scaryAnimals}
  isClearable
  onChange={(opt, meta) => console.log(opt, meta)} />

The isClearable prop allows the current selection to be deleted.

When we type an option that doesn’t currently exist, we are shown a way to add it to the list:

Creatable options

After selecting Rattlesnake, based on the onChange function above, we should end up with a console output that looks like so:

{ label: 'Rattlesnake', value: 'Rattlesnake', __isNew__: true }
{ action: 'create-option' }

You’ll notice that you have two ways of detecting that the event is a new option: the __isNew__ variable of your selected option, and the action value of the meta argument in our event handler.

When using the CreatableSelect component, be sure the value in your options are strings.

Async option loading

Much like the CreatableSelect component, if we want to use async option loading, we’ll need to import AsyncSelect from react-select/lib/Async. The AsyncCreatable component is also available.

To load the options, pass the loadOptions prop, a function, similar to the following:

const loadOptions = (inputValue, callback) => {
  // do some work
  const requestResults = ...

  callback(requestResults)
}

Also available is the defaultOptions prop, which calls the loadOptions function on initialization to populate the dropdown, and the cacheOptions prop, which caches the options while its value is truthy.

Further Reading

A link to documentation for React-Select v2 can be found on the project’s Github page.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#