Implement MultiSelect DropDowns Using React-Select

Introduction

 
In this article, we will learn how we can create searchable and multi select dropdown in React.js using react-select library.
 
Prerequisites
  • We should have basic knowledge of React.js and Web API.
  • Visual Studio and Visual Studio Code IDE should be installed on your system.
  • SQL Server Management Studio
  • Basic knowledge of Bootstrap
  • Axios Installed 

Create ReactJS project

 
Now, let's first create a React application with the following command.
  1. npx create-react-app matform   
Now install react-select using the following command. 
  1. npm install react-select --save  
Now install Bootstrap by using the following commands.
  1. npm install --save bootstrap     
Now, open the index.js file and add import Bootstrap.
  1. import 'bootstrap/dist/css/bootstrap.min.css';    
 Now install the Axios library by using the following command. Learn more about Axios
  1. npm install --save axios    
 Now go to the src folder and add a new component, named 'Reactsel.js'. and import  react-select package.
  1. import Select from 'react-select';  
Add the following code.
  1. import React, { Component } from 'react'  
  2. import Select from 'react-select';  
  3. import axios from 'axios';  
  4.   
  5. export class Reactsel extends Component {  
  6.         constructor(props) {  
  7.                 super(props)  
  8.   
  9.                 this.state = {  
  10.                         country: []  
  11.                 }  
  12.         }  
  13.         componentWillMount() {  
  14.                 axios.get('http://localhost:51983/Api/autoComplete/Countrylist').then(response => {  
  15.                         console.log(response);  
  16.                         this.setState({  
  17.                                 country: response.data  
  18.   
  19.                         })  
  20.                 })  
  21.         }  
  22.         Country() {  
  23.                 return (this.state.country.map(data => ({ label: data.Name, value: data.Id })))  
  24.         }  
  25.         render() {  
  26.                 return (  
  27.                         <>  
  28.                                 <div style={{ margin: "10px" }} class="row" className="hdr">  
  29.                                 <div class="col-sm-12 btn btn-warning">  
  30.                                  React Select  
  31.                                  </div>  
  32.                                 </div>  
  33.                                 <div className="container">  
  34.                                         <div className="row">  
  35.                                                 <div className="col-md-3"></div>  
  36.                                                 <div className="col-md-6">  
  37.                                                         <Select options={this.Country()} />  
  38.                                                 </div>  
  39.                                                 <div className="col-md-4"></div>  
  40.                                         </div>  
  41.                                 </div>  
  42.                         </>  
  43.                 )  
  44.         }  
  45. }  
  46.   
  47. export default Reactsel  
Now run the project by using 'npm start' and check result.
 
Now add another component,named  'Multiselect.js' and  add the following code 
  1. import React, { Component } from 'react';  
  2. import Select from 'react-select';  
  3. import makeAnimated from 'react-select/animated';  
  4. import axios from 'axios';  
  5.   
  6. const animatedComponents = makeAnimated();  
  7. export class Multiselect extends Component {  
  8.         constructor(props) {  
  9.                 super(props)  
  10.   
  11.                 this.state = {  
  12.                         country: [],  
  13.                           
  14.                 }  
  15.         }  
  16.         componentWillMount() {  
  17.                 axios.get('http://localhost:51983/Api/autoComplete/Countrylist').then(response => {  
  18.                         console.log(response);  
  19.                         this.setState({  
  20.                                 country: response.data  
  21.   
  22.                         })  
  23.   
  24.                 })  
  25.   
  26.         }  
  27.         Country() {  
  28.                 return (this.state.country.map(data => ({ label: data.Name, value: data.Id })))  
  29.         }  
  30.           
  31.         render() {  
  32.                 return (  
  33.                         <>  
  34.                                 <div style={{ margin: "10px" }} class="row" className="hdr">  
  35.                                 <div class="col-sm-12 btn btn-warning">  
  36.                                 React Select  
  37.                                 </div>  
  38.                                 </div>  
  39.                                  <div className="container">  
  40.                                  <div className="row">  
  41.                                  <div className="col-md-3"></div>  
  42.                                 <div className="col-md-6">  
  43.                                  <Select  options={this.Country()} components={animatedComponents}  
  44.                                                                         isMulti />  
  45.                                  </div>  
  46.                                  <div className="col-md-4"></div>  
  47.                                  </div>  
  48.                                 </div>  
  49.                            
  50.                         </>  
  51.                 )  
  52.         }  
  53. }  
  54. export default Multiselect  
Now open app.js file and add the following code:
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import Multiselect from './Multiselect'  
  5. import Reactsel from "./Reactsel";  
  6.   
  7. function App() {  
  8.   return (  
  9.     <div className="App">  
  10.       <Multiselect />  
  11.     </div>  
  12.   );  
  13. }  
  14.   
  15. export default App;  

Run the project and check result.

Implement MultiSelect DropDowns Using React-Select

Create a table in the database

 
Open SQL Server Management Studio, create a table:
  1. CREATE TABLE [dbo].[TblCountry](    
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,    
  3.     [Name] [nvarchar](50) NULL,    
  4.  CONSTRAINT [PK_TblCountry] PRIMARY KEY CLUSTERED     
  5. (    
  6.     [Id] ASC    
  7. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]    
  8. ON [PRIMARY]    
  9. GO     

Create a new Web API project

 
Open Visual Studio and create a new project:
 
Implement MultiSelect DropDowns Using React-Select
 
Change the name to autocomplete.
 
Implement MultiSelect DropDowns Using React-Select
 
Choose the template as Web API.
 
Implement MultiSelect DropDowns Using React-Select
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
Implement MultiSelect DropDowns Using React-Select
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
Implement MultiSelect DropDowns Using React-Select
 
Select EF Designer from the database and click the "Next" button.
 
Implement MultiSelect DropDowns Using React-Select
 
Add the connection properties and select database name on the next page and click OK.
 
Implement MultiSelect DropDowns Using React-Select
 
Check the "Table" checkbox. The internal options will be selected by default. Now, click OK
 
Implement MultiSelect DropDowns Using React-Select
 
Now, our data model is successfully created.
 
Right-click on the Controllers folder and add a new controller. Name it as "Autocomplete controller" and add the following namespace in the Autocomplete controller.
  1. using AutoComplete.Models;   
Now add a method to fetch data from database.
  1. public object Getrecord()    
  2. {    
  3.    var data= DB.TblCountries.ToList();    
  4.    return data;    
  5. }   
Complete Autocomplete controller code
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Net;    
  5. using System.Net.Http;    
  6. using System.Web.Http;    
  7. using AutoComplete.Models;    
  8. namespace AutoComplete.Controllers    
  9. {    
  10.     [RoutePrefix("Api/autoComplete")]    
  11.     public class AutoCompleteController : ApiController    
  12.     {    
  13.           AutoCompleteEntities2 DB = new AutoCompleteEntities2();    
  14.             [HttpGet]    
  15.             [Route("Countrylist")]    
  16.             public object Getrecord()    
  17.             {    
  18.              var data= DB.TblCountries.ToList();    
  19.              return data;    
  20.             }    
  21.         }    
  22.     }   
Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");            
  2. config.EnableCors(cors);    
Now go to Visual Studio code and run the project by using 'npm start' command and check.
 
Implement MultiSelect DropDowns Using React-Select 
Implement MultiSelect DropDowns Using React-Select
 

Summary

 
In this article, we learned how we can create searchable and multi select dropdown in React.js using react-select library.