React select dropdown tutorial using react-select.

Manish Mandal
How To React
Published in
3 min readJul 13, 2020

In this tutorial, I will explain how to use the react-select library to create a select dropdown in your react app. For the data, we will be using API from JSON placeholder

Requirements

  1. Open your project directory and install react-select and axios.
npm install axios react-select --save

2. Now open your app.js file. We will be using class component so first, create a constructor and initialize some state.

3. Now create an asynchronous function with the name getOptions and use axios to fetch users data from JSON placeholder API. After getting the response, loop through the array using the javascript map function and create an object with value and label and then change selectOptions value using setState.

4. Now call the above function inside componentDidMount lifecycle method.

5. Now if we console.log our selectOptions inside our render function we will see the options required for react-select.

6. Now import react select in your file import Select from 'react-select' and call that inside return and then pass selectOptions as options inside select tag. After that refresh your browser and see the changes

7. Now let us create a function that will handle our selected value. Create a function with the name handleChange and take e as a parameter and after that change the value of id and name using the setState function

8. Now assign your handleChange event on onChange method inside select tag and bind it.

Here is the final app.js code.

isMulti

Now it’s time to create multiple options.

  1. Add isMulti inside the Select tag.

2. Now remove id and name from step 2 above and add value as a blank array.

2. Now inside handleChange function set value state as e using setState.

3. Now loop through value inside render using map function to display all our selected options. We are also checking the value whether it’s null or not using the ternary operator so that we don’t get any error by removing the last selected option.

That’s it for today here is the git repository and live code.

--

--

Manish Mandal
How To React

Full Stack Developer | React JS | Next JS | Node JS | Vue JS | Wordpress. Connect with me https://www.linkedin.com/in/manishmandal21/