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 and React Select Example Using Material UI.
Here, I am creating the same above functionality using rest API with async.
Video Tutorial
If you are more comfortable in watching a video that explains Async React-Select Dropdown using Rest API, then you should watch this video tutorial.
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 customized.
- 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.
Checkout Other tutorials:
- How To Handle Routing In React Using BrowserRouter
- React Layout Using Material Design
- React File Upload In 5 Minute
Dynamically Create Dropdown Using React
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
Generate Dropdown List Using React
We’ll create an 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 the above file on the top of the app.js
file. Let’s open the src/App.js
file and add the below code in this file:
// App.js import React,{ useState, useEffect } from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import dummy from './api/dummy' import AsyncSelect from 'react-select/async'; function App() { const [items, setItems] = useState([]); const [inputValue, setValue] = useState(''); const [selectedValue, setSelectedValue] = useState(null); // handle input change event const handleInputChange = value => { setValue(value); }; // handle selection const handleChange = value => { setSelectedValue(value); } const fetchData = () => { return dummy.get('/users?page=1').then(result => { const res = result.data.data; return res; }); } return ( Selected Value: {JSON.stringify(selectedValue || {}, null, 2)} e.first_name + ' ' + e.last_name} getOptionValue={e => e.id} loadOptions={fetchData} onInputChange={handleInputChange} onChange={handleChange} /> ); } export default App
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 to fetch data 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.