Convert Figma logo to code with AI

JedWatson logoreact-select

The Select Component for React.js

27,531
4,116
27,531
433

Top Related Projects

12,045

🏎 A set of primitives to build simple, flexible, WAI-ARIA compliant React autocomplete, combobox or select dropdown components.

Polished, feature rich, accessible form inputs built with React

HOC that uses react-virtualized and react-select to display large lists of options in a drop-down

Quick Overview

React-select is a flexible and customizable select input control for ReactJS. It provides a robust solution for creating searchable dropdown menus with support for single and multi-select options, async data loading, and extensive styling capabilities.

Pros

  • Highly customizable with a wide range of options and themes
  • Supports both single and multi-select functionality
  • Offers async data loading for handling large datasets
  • Provides excellent accessibility features and keyboard navigation

Cons

  • Can be complex to set up for advanced use cases
  • Performance may degrade with very large option lists
  • Some users report issues with TypeScript definitions
  • Learning curve can be steep for newcomers to React

Code Examples

  1. Basic usage:
import Select from 'react-select';

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

const MyComponent = () => (
  <Select options={options} />
);
  1. Multi-select:
import Select from 'react-select';

const MyComponent = () => (
  <Select
    isMulti
    options={options}
    placeholder="Select multiple flavors..."
  />
);
  1. Async loading:
import AsyncSelect from 'react-select/async';

const loadOptions = (inputValue, callback) => {
  setTimeout(() => {
    callback(filterOptions(inputValue));
  }, 1000);
};

const MyComponent = () => (
  <AsyncSelect loadOptions={loadOptions} />
);

Getting Started

  1. Install the package:

    npm install react-select
    
  2. Import and use in your React component:

    import Select from 'react-select';
    
    const options = [
      { value: 'option1', label: 'Option 1' },
      { value: 'option2', label: 'Option 2' },
    ];
    
    function MyComponent() {
      return (
        <Select
          options={options}
          onChange={(selectedOption) => console.log(selectedOption)}
        />
      );
    }
    
  3. Customize as needed using props and styles.

Competitor Comparisons

12,045

🏎 A set of primitives to build simple, flexible, WAI-ARIA compliant React autocomplete, combobox or select dropdown components.

Pros of downshift

  • More flexible and customizable, allowing for greater control over UI and behavior
  • Smaller bundle size, which can lead to better performance
  • Follows WAI-ARIA practices, ensuring better accessibility out of the box

Cons of downshift

  • Requires more setup and configuration compared to react-select's ready-to-use components
  • Less built-in styling options, potentially requiring more custom CSS work
  • Steeper learning curve for developers new to the library

Code Comparison

downshift:

<Downshift
  onChange={selection => handleChange(selection)}
  itemToString={item => (item ? item.value : '')}
>
  {({ getInputProps, getItemProps, isOpen, inputValue, selectedItem, highlightedIndex }) => (
    <div>
      <input {...getInputProps()} />
      {isOpen && (
        <div>
          {items
            .filter(item => !inputValue || item.value.includes(inputValue))
            .map((item, index) => (
              <div
                {...getItemProps({
                  key: item.value,
                  index,
                  item,
                  style: {
                    backgroundColor: highlightedIndex === index ? 'lightgray' : 'white',
                    fontWeight: selectedItem === item ? 'bold' : 'normal',
                  },
                })}
              >
                {item.value}
              </div>
            ))}
        </div>
      )}
    </div>
  )}
</Downshift>

react-select:

<Select
  options={options}
  onChange={handleChange}
  value={selectedOption}
/>

The code comparison demonstrates the difference in complexity and customization between the two libraries. downshift requires more setup but offers greater flexibility, while react-select provides a simpler, more straightforward implementation.

Polished, feature rich, accessible form inputs built with React

Pros of react-widgets

  • Offers a wider range of form components beyond just select inputs
  • Provides more customization options for styling and behavior
  • Includes built-in localization support for multiple languages

Cons of react-widgets

  • Less focused on select functionality, which may result in fewer select-specific features
  • Larger bundle size due to the inclusion of multiple components
  • Less frequent updates and potentially slower bug fixes compared to react-select

Code Comparison

react-select:

import Select from 'react-select';

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

<Select options={options} />

react-widgets:

import { DropdownList } from 'react-widgets';

const options = ['Chocolate', 'Strawberry', 'Vanilla'];

<DropdownList
  data={options}
  defaultValue="Chocolate"
/>

Both libraries offer similar functionality for creating dropdown selects, but react-widgets uses a different approach with separate components for different types of inputs. react-select focuses specifically on select inputs, while react-widgets provides a broader range of form components.

HOC that uses react-virtualized and react-select to display large lists of options in a drop-down

Pros of react-virtualized-select

  • Efficient rendering of large lists using virtualization
  • Better performance with large datasets
  • Seamless integration with react-virtualized components

Cons of react-virtualized-select

  • Less actively maintained compared to react-select
  • Fewer built-in features and customization options
  • Steeper learning curve for developers unfamiliar with virtualization concepts

Code Comparison

react-virtualized-select:

import VirtualizedSelect from 'react-virtualized-select';

<VirtualizedSelect
  options={largeDataset}
  onChange={selectValue}
  virtualized
/>

react-select:

import Select from 'react-select';

<Select
  options={largeDataset}
  onChange={selectValue}
/>

The main difference in usage is the virtualized prop in react-virtualized-select, which enables the virtualization feature. react-select doesn't require this prop as it doesn't offer built-in virtualization.

react-virtualized-select is particularly useful for rendering large lists efficiently, while react-select offers a wider range of features and customization options. The choice between the two depends on the specific requirements of your project, such as dataset size and desired functionality.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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. We are an open source project that is continously supported by the community.

React Select helps you develop powerful select components that just work out of the box, without stopping you from customising the parts that are important to you.

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:

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 programmatically
  • blur() - blur the control programmatically

Customisation

Check the docs for more information on:

TypeScript

The v5 release represents a rewrite from JavaScript to TypeScript. The types for v4 and earlier releases are available at @types. See the TypeScript guide for how to use the types starting with v5.

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, Emma 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 2022.

NPM DownloadsLast 30 Days