Code Premix

How to create a dropdown in React using react-select

๐Ÿ“…November 22, 2021|๐Ÿ—React

In this article, we will show you how to create a dropdown in React using react-select.

  • 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
  1. Installation
  2. Usage
  3. Output

1. Installation

npm i react-select

2. Usage

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

function App() {
  const data = [
    { value: 100, label: "cerulean" },
    { value: 200, label: "fuchsia rose" },
    { value: 300, label: "true red" },
    { value: 400, label: "aqua sky" },
    { value: 500, label: "tigerlily" },
    { value: 600, label: "blue turquoise" }
  ];

  const [selectedOption, setSelectedOption] = useState(null);

  // handle onChange event of the dropdown
  const handleChange = e => {
    setSelectedOption(e);
  }

  return (
    <div className="app">
      <h4>Dropdown using react-select <a href="https://codepremix.com">Code Premix</a></h4>

      <Select
        placeholder="Select Option"
        value={selectedOption} // set selected value
        options={data} // set list of the data
        onChange={handleChange} // assign onChange function
      />

      {selectedOption && <div className="output">
        <b>Selected Option</b><br />
        <div style={{ marginTop: 10 }}><b>Label: </b> {selectedOption.label}</div>
        <div><b>Value: </b> {selectedOption.value}</div>
      </div>}
    </div>
  );
}

export default App;

3. Output

Demo & Source Code

GitHub Repository