In our previous React tutorial, we have explained how to create react select dropdown. In this tutorial, you will learn to create React Select Dropdown List using REST API.
We will use react-select
library to create an async select dropdown list by making http client request to API using axios
package and loading response data to dropdown list. We will also use useState
hooks to set and get selected values.
So let’s start with tutorial to create react select dropdown using REST API.
Prerequisites
React Application Setup
First we will create React application using the create-react-app
command. Here we will create react-dropdown-api
react application to create select dropdown and load dropdown list using REST API.
npx create-react-app react-dropdown-api
Now go inside project folder.
cd react-dropdown-api
Install React-Select Library
Now we will run following command to install the react-select
library.
npm install react-select --save ##### or ##### yarn add react-select
Install Bootstrap for Styling
We will install Bootstrap 4 for adding style to react select dropdown component.
npm install bootstrap --save ##### or ##### yarn add bootstrap
Install Axios HTTP Client
As here in this tutorial, we will load react select dropdown list by retrieving data from the REST API. So here will install axios
http client to make HTTP request to API.
npm install axios –save # or yarn add axios
Create Component File for API Call
We will create src/api
directory and create src/api/myApi.js
file. In myApi.js
file, we will import axios
package and created an instance with all default parameters. We will set the default baseurl in Axios with API url. Now we need to import myApi.js
file throughout our application where we need to make an API call.
import axios from 'axios'; export default axios.create({ baseURL: 'https://reqres.in/api', headers: { }, });
Create React Select Dropdown List with API
In app.js
file, we will import myApi.js
file and get user JSON data from API. We will load response JSON data into select dropdown and display on dropdown option select.
import React,{ useState, useEffect } from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import myApi from './api/myApi' 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 fetchUsers = () => { return myApi.get('/users?page=1').then(result => { const res = result.data.data; return res; }); } return ( <div className="container"> <div className="row"> <div className="col-md-4"> </div> </div> <div className="row"> <div className="col-md-4"></div> <div className="col-md-4"> <AsyncSelect cacheOptions defaultOptions value={selectedValue} getOptionLabel={e => e.first_name + ' ' + e.last_name} getOptionValue={e => e.id} loadOptions={fetchUsers} onInputChange={handleInputChange} onChange={handleChange} /> </div> <div className="col-md-4"></div> </div> <div className="row userDetails"> <div className="col-md-6 img"> <img src={ selectedValue && selectedValue.avatar } className="img-rounded"/> </div> <div className="col-md-6"> <blockquote > <h5>{ selectedValue && selectedValue.first_name} { selectedValue && selectedValue.last_name}</h5> <small><cite title="Source Title"> { selectedValue && selectedValue.email }<i className="icon-map-marker"></i></cite></small> </blockquote> </div> </div> </div> ); } export default App
In above code, we have imported all dependencies at the top, defined states variables and EventHandler methods. We have created a function fetchUsers
to fetch the user list by making HTTP request to API using axios
HTTP Get method. We have also used AsyncSelect
component and passed fetchUsers
method to render the async component and display the user data in select dropdown. We are also displaying users data according to dropdown selection.
Run React Application
Now we will run our React application using blow command:
npm start
The application will be avaible on http://localhost:3000/
and it run automaticaly in a browser.