The Select Component for React.js

Last update: Aug 4, 2022

NPM CircleCI Coverage Status Supported by Thinkmill

React-Select

The Select control for React. Initially built for use in KeystoneJS.

See react-select.com for live demos and comprehensive docs.

React Select is funded by Thinkmill and Atlassian. It represents a whole new approach to developing powerful React.js components that just work out of the box, while being extremely customisable.

For the story behind this component, watch Jed's talk at React Conf 2019 - building React Select

Features include:

  • Flexible approach to data, with customisable functions
  • Extensible styling API with emotion
  • Component Injection API for complete control over the UI behaviour
  • Controllable state props and modular architecture
  • Long-requested features like option groups, portal support, animation, and more

Using an older version?

Installation and usage

The easiest way to use react-select is to install it from npm and build it into your app with Webpack.

yarn add react-select

Then use it in your app:

With React Component

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

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

class App extends React.Component {
  state = {
    selectedOption: null,
  };
  handleChange = selectedOption => {
    this.setState(
      { selectedOption },
      () => console.log(`Option selected:`, this.state.selectedOption)
    );
  };
  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        onChange={this.handleChange}
        options={options}
      />
    );
  }
}

With React Hooks

import React, { useState } from "react";
import Select from "react-select";

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

export default function App() {
  const [selectedOption, setSelectedOption] = useState(null);
  
  return (
    <div className="App">
      <Select
        defaultValue={selectedOption}
        onChange={setSelectedOption}
        options={options}
      />
    </div>
  );
}

Props

Common props you may want to specify include:

  • autoFocus - focus the control when it mounts
  • className - apply a className to the control
  • classNamePrefix - apply classNames to inner elements with the given prefix
  • isDisabled - disable the control
  • isMulti - allow the user to select multiple values
  • isSearchable - allow the user to search for matching options
  • name - generate an HTML input with this name, containing the current value
  • onChange - subscribe to change events
  • options - specify the options the user can select from
  • placeholder - change the text displayed when no option is selected
  • noOptionsMessage - ({ inputValue: string }) => string | null - Text to display when there are no options
  • value - control the current value

See the props documentation for complete documentation on the props react-select supports.

Controllable Props

You can control the following props by providing values for them. If you don't, react-select will manage them for you.

  • value / onChange - specify the current value of the control
  • menuIsOpen / onMenuOpen / onMenuClose - control whether the menu is open
  • inputValue / onInputChange - control the value of the search input (changing this will update the available options)

If you don't provide these props, you can set the initial value of the state they control:

  • defaultValue - set the initial value of the control
  • defaultMenuIsOpen - set the initial open value of the menu
  • defaultInputValue - set the initial value of the search input

Methods

React-select exposes two public methods:

  • focus() - focus the control programatically
  • blur() - blur the control programatically

Customisation

Check the docs for more information on:

Thanks

Thank you to everyone who has contributed to this project. It's been a wild ride.

If you like React Select, you should follow me on twitter!

Shout out to Joss Mackison, Charles Lee, Ben Conolly, Tom Walker, Nathan Bierema, Eric Bonow, Mitchell Hamilton, Dave Brotherstone, Brian Vaughn, and the Atlassian Design System team who along with many other contributors have made this possible ❤️

License

MIT Licensed. Copyright (c) Jed Watson 2021.

GitHub

https://github.com/JedWatson/react-select
Comments
  • 1. feat(pagination): add async pagination

    This checks the first box in this list for v1.0.0 and closes #644

    This adds a new pagination prop to the Select.Aync component. It is a boolean which is false by default (false: things act as they did before it was added). When pagination is true loadOptions is given an additional argument; page. page tells the user's loadOptions function which page to load (they can use to when building their request). Additional page results are appended to the options list. Changing the input value will reset the page back to 1. loadOptions is called when the user scrolls to the bottom of the menu list, trigger the next page of results to be appended. Caching is used! (Cache all the things!). If a user scrolls down enough to load additional pages, then changes the input (triggering new requests), then enters the original input, all of the pages for the original input will be loaded back and when the user scroll to the bottom again, it will pick up on the page it left off on.

    Documentation has been updated to reflect the new prop and how it affects loadOptions' signature.

    EDIT: async-pagination

    Reviewed by TheSharpieOne at 2016-09-21 20:02
  • 2. positioning the component in containers that have `overflow: scroll;`

    I recently ran into this issue when using react-select components in a modal. For mobile the contents of the modal are scrollable. In this particular case, the Select was at the bottom of the content. Activating the Select made the container overflow and scrollable.

    Maybe the container notion of http://react-bootstrap.github.io/react-overlays/examples/ might make sense? Alternatively, maybe make use of https://github.com/souporserious/react-tether?

    Reviewed by ksmth at 2016-03-02 10:57
  • 3. Implemented allowCreate and more flexible add item on comma functionality

    I took the pull request #660 (which relates to #658 and #586) and re-did it as this is a huge show stopper for me on using this library and that implementation seemed a bit broken (and the 0.9.1 does not have some of the functionality that I also need the 1.0.0-beta does).

    This adds back in the allowCreate functionality with the tests reworked to pass (I also fixed an existing failing test as it seemed to be using the old setPropselectorChild method instead of setPropsForChild)

    UPDATE:

    I added another commit here to add a more flexible solution to the old add item on comma when allowCreate and mutli are enabled. My solution allows you to specific the keyCode to use to add a new item (set with the addItemOnKeyCode prop). While comma is pretty common, it is not always the best option and making it flexible like this it not that much difference in the implementation. This also allows you to turn off this feature which was not possible in the older implementation which i think is not completely uncommon. By default the addItemOnKeyCode prop is set to null so that the user need to explicitly enable this functionality.

    Also, I have no idea what the @coveralls messages mean. I did run coverage reports before and after and the coverage did not go down after my src / test updates (they actually went up on 1 or 2 src files but only marginally).

    If I could get an update if this will be an acceptable PR (or if any changes are needed to get this merged) and included into a npm tagged beta release relatively soon that would be great. Without these changes, using this library is a show stopper. Since 0.9.1 is also missing functionality the 1.x beta version has, using that version is also a show stopper. If these features are not going to be able to be consumable through npm relatively soon, I am going to have to publish my own version to be able to move forward with this library which I would prefer not to do.

    Reviewed by ryanzec at 2016-06-01 18:39
  • 4. Z-Index Problems?

    image

    I had this problem with a default install of react-select ? I can't seem to figure it out, I have spent hours on this. It appears near impossible to get the dropdown to be above everything... perhaps some sort of portal solution should be used for this ?

    Reviewed by bradennapier at 2016-07-13 03:44
  • 5. Control opening direction up/down

    Hi! Is there a way to control the opening direction programmatically? kinda like the native select tag behavior, opens up or down (when there is not enough space for the dropdown to open up ). thanks!

    Reviewed by BenGedi at 2015-06-30 06:57
  • 6. onChange returns the selected value, not the complete event

    onChange simply returns the new value and label and not the whole event.

    I understand we can use the hidden input field to fire an onChange but this does not happen automatically and while we can manually fire an onChange for hidden input field, we can also wrap an event around the Select. Here is how I am doing it following #520:

    <Select
      name="form-field-name"
      value={val}
      options={options}
      onChange={(val)=> {onChangeFunc({target: { name:'revision_id', value: val.value }})}}
    />
    

    Creating an object myself and passing it to my onChange handler. Is this the right way to do it or you can suggest a better way around it?

    Reviewed by OsamaShabrez at 2017-03-28 16:22
  • 7. Debouncing support

    Hi there, I was wondering there is a way to "debounce" async option loading with react-select. Currently, I'm seeing queries like this:

    image

    I would like react-select to only query after a 250ms typing pause. What do I need to do to make react-select do this? I have tried wrapping my function in a setTimeout, but that does not appear to do anything:

      taxons (input, callback) {
        setTimeout(function () {
          $.ajax({
            url: '/api/v2/taxons/search',
            dataType: 'json',
            cache: false,
            data: { name: input },
            success: function (response) {
              var options = response.data.map(function(taxon, index) {
                return (
                  { value: taxon.id, label: taxon.attributes.tree_name }
                );
              });
    
              callback(null, {
                options: options
              })
            }
          })
        }, 250)
      }
    
    Reviewed by radar at 2015-11-23 03:34
  • 8. Support inline-block / sizes

    react-select only seems to work as a full-width block component. It would be nice if it would also support use as an inline-block component (like a standard <select>) with either an auto-calculated width or a specified width.

    Reviewed by dantman at 2015-07-19 07:58
  • 9. Rewrite / 1.0

    I'm midway through a massive rewrite of this library and wanted to open an issue so it's more visible. There will be several breaking changes to the API, all for the better.

    WIP is visible on the rebuild branch.

    Aside from how we're bundling lib and dist files (which won't change for now), it basically addresses all the things that @brianreavis raised in #227.

    I've been trying to split Select up into more granular components as suggested by @bruderstein in #396, but it's not obvious how to do this while also cleaning everything up and preserving a simple API so that can probably be the focus of another major version down the track.

    The big improvements include:

    • Everything is simpler (I'm nearly done and the source code is only 60% of the size of the last version)
    • No more timeouts or weird handlers, the restructuring has let me make everything more straight-forward
    • The options array is no longer preprocessed into state, just retrieved from props
    • The values array is now initialised in the Options array during render, and not stored in state, which along with the change to options makes the component more reliable and fixes issues with props not updating correctly
    • The component no longer stores its own value in state (ever) - it needs to be passed as a prop and handled with onChange.
    • Complex values are now enabled by default (so you're passed the option object, not its value); you can enable the legacy mode with a prop
    • The Value and Option components have been cleaned up as well for consistency
    • The hidden <input> field is now optional and the component is better suited to use in a rich React.js app than it was
    • You can disable options filtering to do the filtering externally with onInputChange
    • Accents on characters can now be ignored

    The other major change is that the whole async options loading piece has been split out into its own Select.Async component, which wraps Select and passes most props through. This dramatically simplifies the select component itself, and plays nicely with the new "options and value are just props" changes. Props that were related to asyncOptions have also been moved to the new component.

    Aside from the details of what's been changed, it just feels better to use, more solid. I don't have benchmarks to back this up, but it should be much faster too (and easier to optimise in subsequent versions)

    Reviewed by JedWatson at 2015-11-03 14:40
  • 10. Update MenuPlacer context usage to the new context API

    This solves #3916, and partially addresses #3703.

    From React 16.3 the old Context API was deprecated and it's rising warnings when runng in strict-mode.

    Reviewed by dpordomingo at 2020-02-11 11:34
  • 11. [v2] react-select didn't work for long lists

    Hi there

    I'm testing out react-select v2 and I noticed performance issues once when I have a long lists of 300,000 items. I wanted to know if there is any interest to build in something like react-virtualized into react-select so users can scroll through long lists without jank or is this out of scope of this project.

    Thanks.

    Reviewed by kahwee at 2018-07-25 05:41
  • 12. Docs is outdated.

    Docs is outdated.

    https://react-select.com/styles#cx-and-custom-components

    • cx works different now.

    It should be - (state?: {}, className?: string) => string

    image


    • getStyles example should import @emotion/css and update cx usage.

    image

    Reviewed by igoryusha at 2022-08-02 11:09
  • 13. CSS modules not being loaded when classes have hashes

    Hello, in the project I'm working on we're using ComponentName.modules.css files for modular styling, with no preprocessors, and so far I've been trying to have the same work with react-select without success. Apparently it doesn't recognize classes with hashes out of the box, so the properties "className" and "classNamePrefix" haven't been working as intended.

    Is there any workaround that doesn't involve using a preprocessor, the style API, applying the styles to :global (which defeats the purpose of using CSS modules in the first place) or using ComponentName.styles.css (which also defeats the purpose)? We'd like to keep using CSS modules to keep the project organization consistent for future documentation.

    Reviewed by VicMCA at 2022-07-29 15:46
  • 14. Bump terser from 4.8.0 to 4.8.1

    Bumps terser from 4.8.0 to 4.8.1.

    Changelog

    Sourced from terser's changelog.

    v4.8.1 (backport)

    • Security fix for RegExps that should not be evaluated (regexp DDOS)
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    Reviewed by dependabot[bot] at 2022-07-20 01:32
  • 15. Add missing declaration to CustomSelectProps.tsx example

    Re-ticketed from https://github.com/JedWatson/react-select/issues/4804#issuecomment-1030480301

    The mention of type declarations is in the docs, but missing from the example, where we still use @ts-ignore. We should add this declaration to the example itself :)

    (I spent a few days cycling on this, as I was operating out of the examples, and didn't quite realize how important the ts-ignore line was. This is def "user error", but I thought having it reflected in the example code might help people not trip up like me!)

    Reviewed by patcon at 2022-07-15 19:34
  • 16. Option value like id

    https://github.com/JedWatson/react-select/blob/4b8468636bcfadf0cfe45f9a7a6c1db5dca08d9a/packages/react-select/src/Select.tsx#L1884

    It will be very nice to have opportunity, to use value from options list in option id {input-id}-{option-value}

    Reviewed by andrewright at 2022-07-14 14:55
Related tags
Micro-sized & micro-optimized select component for React.js

React-Functional-Select Micro-sized & micro-optimized select component for React.js. Key features: Fully-featured package that is truly lightweight: <

Jul 3, 2022
An accessible select box component for React.

React Select Box An accessible select box component for React. Demo http://instructure-react.github.io/react-select-box/ Installation $ npm install re

Jul 9, 2022
The Select Component for React.js

React-Select The Select control for React. Initially built for use in KeystoneJS. See react-select.com for live demos and comprehensive docs. React Se

Aug 4, 2022
A React multi-select component using Material-UI

A component to select multiple items from a list of options using the Material-UI Autocomplete component.

Jun 29, 2021
React component to select options by transferring them from one column to another.

React component to select options by transferring them from one column to another.

May 22, 2022
A react component to manage nested select tags

nested-selects-react nestedSelectsReact A react component to manage nested <select> tags. install with npm: npm i nested-selects-react install with y

May 8, 2021
📝 Select Component for React

reaselct Select Component for React ?? Quick Links Docs and Demos CodeSandbox ?? Features Single Select Multi Select Filtering with Fuzzy Search Async

Jul 26, 2022
Spring-chain - A custom select component with a menu with animations and beautiful gradients Built With React

Spring Chain We built a custom select component with a menu with animations and

Feb 6, 2022
A react component for custom flag (country code) select. Online demo examples
A react component for custom flag (country code) select. Online demo examples

react-custom-flag-select A react component for custom flag (country code) select. Online Demo Live demo Codesandbox Examples Live demo playground ?? F

Jun 27, 2022
Selecto.js is a component that allows you to select elements in the drag area using the mouse or touch.
Selecto.js is a component that allows you to select elements in the drag area using the mouse or touch.

Selecto.js is a component that allows you to select elements in the drag area using the mouse or touch.

Jul 27, 2022
Simple and lightweight multiple selection dropdown component with checkboxes, search and select-all
Simple and lightweight multiple selection dropdown component with checkboxes, search and select-all

Lightweight (~5KB gzipped) multiple selection dropdown component

Jul 29, 2022
React hooks for building select and combobox components

React hooks for building select and combobox components

Nov 15, 2021
The Select control for React. Initially built for use in KeystoneJS.

The Select control for React. Initially built for use in KeystoneJS.

Oct 1, 2021
Customisable dropdown select for react

react-dropdown-select Customisable dropdown select for react Features configurable via props total custom components overrides for all internals via r

Aug 6, 2022
A React library that provides a customizable SVG flags select components and standalone SVG flags components.

A React library that provides a customizable SVG flags select components and standalone SVG flags components.

Jul 29, 2022
A React chinese city selector component
A React chinese city selector component

react-chinese-city-selector A React chinese city selector component Install npm install react-chinese-city-selector Usage import CitySelector from "r

Jan 13, 2022
A fully accessible, easily themeable, React-powered menu button

react-aria-menubutton A React component (set of components, really) that will help you build accessible menu buttons by providing keyboard interaction

Jul 28, 2022
Autocomplete input field for React
Autocomplete input field for React

react-autocomplete-input Autocomplete input field for React Demo Demo and playground are available here Usage Example import TextInput from 'react-aut

Jul 15, 2022
🌐 An extremely usable and dynamic React timezone selector

?? An extremely usable and dynamic React timezone selector

Aug 2, 2022