React-Select Async Dropdown using Rest API
This tutorial will show you how to use react-select to create an async dropdown. I’m also utilising useState hooks to set and receive selected values, as well as Axios to retrieve data from the rest API.
I have already shared tutorial Create React Dropdown Select without Async.
Here, I am creating the same above functionality using rest API with async.
What’s react-select library
React-select is a flexible and beautiful Select Input control for ReactJS with multiselect, autocomplete, async and creatable support.This library includes features such as search/filter items, ajax operation, and so on.
It has the following features:
- Flexible approach to data, with functions that can be customised.
- Extensible styling API with emotion.
- Component Injection API for complete control over the UI behavior.
- Controllable state props and modular architecture.
- Long-requested features like option groups, portal support, animation, and more.
Let’s make a react app that generates a dropdown list dynamically. All requirements will be installed with the following command:
Install React and other libraries
Let’s create a react application using create-react-app :
npx create-react-app reactselect-poc
Now, navigate to the project folder.
cd reactselect-poc
install React-Select v2
Use the following command to add the react-select package to your React-Select v2 installation.
yarn add react-select
# or
npm install react-select -save
Install Bootstrap 4
install Bootstrap 4 using the following command.
yarn add bootstrap
# or
npm install bootstrap -save
How To install Axios
Use the following command to add the react-select package to your React-Select v2 installation.
yarn add axios
# or
npm install axios -save
We’ll create api method into the scr/api/dummy.js file:
import axios from ‘axios’;
export default axios.create({
baseURL: ‘https://reqres.in/api',
headers: {
},
});
We’ll import above file on the top of the app.js file.Let’s open the src/App.js file and added below code in this file:
There are following steps added in the above code:
- Imported all dependencies at top of the file
- Define states variables
- Define EventHandler methods
- Create a function fetchData to fetch the list where we will integrate the API using the axios HTTP Get method.
- I used AsyncSelect component and passed fetchData method to render the async component and display the values across the page.
- We have used the getOptionLabel and getOptionValue to manage the attribute first_name/last_name for label and id for value in dropdown.
Originally published at https://www.js-tutorials.com on October 16, 2021.