spmjs

spm@3.x

Brand new static package manager for browser.

Getting Started 󰅴 Packages

react-select


A Select control built with and for ReactJS

spm install react-select

NPM Build Status Coverage Status

React-Select

A Select control built with and for React. Initially built for use in KeystoneJS.

New version 1.0.0-beta

I've nearly completed a major rewrite of this component (see issue #568 for details and progress). The new code has been merged into master, and react-select@1.0.0-beta has been published to npm and bower.

1.0.0 has some breaking changes. The documentation below still needs to be updated for the new API; notes on the changes can be found in CHANGES.md and will be finalised into HISTORY.md soon.

Our tests need some major updates to work with the new API (see #571) and are causing the build to fail, but the component is stable and robust in actual usage.

Testing, feedback and PRs for the new version are appreciated.

Demo & Examples

Live demo: jedwatson.github.io/react-select

The live demo is still running v0.9.1.

To build the new 1.0.0 examples locally, clone this repo then run:

npm install
npm start

Then open localhost:8000 in a browser.

Installation

The easiest way to use React-Select is to install it from NPM and include it in your own React build process (using Browserify, etc).

npm install react-select --save

You can also use the standalone build by including dist/react-select.js and dist/react-select.css in your page. If you use this, make sure you have already included the following dependencies:

Usage

React-Select generates a hidden text field containing the selected value, so you can submit it as part of a standard form. You can also listen for changes with the onChange event property.

Options should be provided as an Array of Objects, each with a value and label property for rendering and searching. You can use a disabled property to indicate whether the option is disabled or not.

The value property of each option should be set to either a string or a number.

When the value is changed, onChange(newValue, [selectedOptions]) will fire.

var Select = require('react-select');

var options = [
    { value: 'one', label: 'One' },
    { value: 'two', label: 'Two' }
];

function logChange(val) {
    console.log("Selected: " + val);
}

<Select
    name="form-field-name"
    value="one"
    options={options}
    onChange={logChange}
/>

Multiselect options

You can enable multi-value selection by setting multi={true}. In this mode:

Async options

If you want to load options asynchronously, instead of providing an options Array, provide a loadOptions Function.

The function takes two arguments String input, Function callbackand will be called when the input text is changed.

When your async process finishes getting the options, pass them to callback(err, data) in a Object { options: [] }.

The select control will intelligently cache options for input strings that have already been fetched. The cached result set will be filtered as more specific searches are input, so if your async process would only return a smaller set of results for a more specific query, also pass complete: true in the callback object. Caching can be disabled by setting cache to false (Note that complete: true will then have no effect).

Unless you specify the property autoload={false} the control will automatically load the default set of options (i.e. for input: '') when it is mounted.

var Select = require('react-select');

var getOptions = function(input, callback) {
    setTimeout(function() {
        callback(null, {
            options: [
                { value: 'one', label: 'One' },
                { value: 'two', label: 'Two' }
            ],
            // CAREFUL! Only set this to true when there are no more options,
            // or more specific queries will not be sent to the server.
            complete: true
        });
    }, 500);
};

<Select.Async
    name="form-field-name"
    loadOptions={getOptions}
/>

Async options with Promises

loadOptions supports Promises, which can be used in very much the same way as callbacks.

Everything that applies to loadOptions with callbacks still applies to the Promises approach (e.g. caching, autoload, ...)

An example using the fetch API and ES6 syntax, with an API that returns an object like:

import Select from 'react-select';

/*
 * assuming the API returns something like this:
 *   const json = [
 *        { value: 'one', label: 'One' },
 *        { value: 'two', label: 'Two' }
 *   ]
 */

const getOptions = (input) => {
  return fetch(`/users/${input}.json`)
    .then((response) => {
      return response.json();
    }).then((json) => {
      return { options: json };
    });
}

<Select.Async
    name="form-field-name"
    value="one"
    loadOptions={getOptions}
/>

Async options loaded externally

If you want to load options asynchronously externally from the Select component, you can have the Select component show a loading spinner by passing in the isLoading prop set to true.

var Select = require('react-select');

var isLoadingExternally = true;

<Select
  name="form-field-name"
    isLoading={isLoadingExternally}
    ...
/>

Filtering options

You can control how options are filtered with the following properties:

matchProp and matchPos both default to "any". ignoreCase defaults to true.

Advanced filters

You can also completely replace the method used to filter either a single option, or the entire options array (allowing custom sort mechanisms, etc.)

For multi-select inputs, when providing a custom filterOptions method, remember to exclude current values from the returned array of options.

Effeciently rendering large lists with windowing

The menuRenderer property can be used to override the default drop-down list of options. This should be done when the list is large (hundreds or thousands of items) for faster rendering. The custom menuRenderer property accepts the following named parameters:

Parameter Type Description
focusedOption Object The currently focused option; should be visible in the menu by default.
focusOption Function Callback to focus a new option; receives the option as a parameter.
labelKey String Option labels are accessible with this string key.
options Array<Object> Ordered array of options to render.
selectValue Function Callback to select a new option; receives the option as a parameter.
valueArray Array<Object> Array of currently selected options.

Windowing libraries like react-virtualized can then be used to more efficiently render the drop-down menu like so:

menuRenderer({ focusedOption, focusOption, labelKey, options, selectValue, valueArray }) {
  const focusedOptionIndex = options.indexOf(focusedOption);
  const option = options[index];
  const isFocusedOption = option === focusedOption;

  return (
    <VirtualScroll
      ref="VirtualScroll"
      height={200}
      rowHeight={35}
      rowRenderer={(index) => (
        <div
          onMouseOver={() => focusOption(option)}
          onClick={() => selectValue(option)}
        >
          {option[labelKey]}
        </div>
      )}
      rowsCount={options.length}
      scrollToIndex={focusedOptionIndex}
      width={200}
    />
  )
}

Check out the demo site for a more complete example of this.

Further options

Property    |    Type        |    Default        |    Description

:-----------------------|:--------------|:--------------|:-------------------------------- addLabelText | string | 'Add "{label}"?' | text to display when allowCreate is true autosize | bool | true | If enabled, the input will expand as the length of its value increases autoBlur | bool | false | Blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices allowCreate | bool | false | allow new options to be created in multi mode (displays an "Add \

Methods

Right now there's simply a focus() method that gives the control focus. All other methods on <Select> elements should be considered private and prone to change.

// focuses the input element
<instance>.focus();

Contributing

See our CONTRIBUTING.md for information on how to contribute.

Thanks to the projects this was inspired by: Selectize (in terms of behaviour and user experience), React-Autocomplete (as a quality React Combobox implementation), as well as other select controls including Chosen and Select2.

License

MIT Licensed. Copyright (c) Jed Watson 2016.