8

Async React-Select Dropdown using Rest API

 2 years ago
source link: https://www.js-tutorials.com/react-js/react-select-async-dropdown-using-rest-api/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.

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 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:

// 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 (
  <div className="container">
    <div className="row alert alert-info">Selected Value: {JSON.stringify(selectedValue || {}, null, 2)}</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={fetchData}
        onInputChange={handleInputChange}
        onChange={handleChange}
      />
      </div>
      <div className="col-md-4"></div>
    </div>
  </div>
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 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.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK