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. export class Reactsel extends Component {
  5. constructor(props) {
  6. super(props)
  7. this.state = {
  8. country: []
  9. }
  10. }
  11. componentWillMount() {
  12. axios.get('http://localhost:51983/Api/autoComplete/Countrylist').then(response => {
  13. console.log(response);
  14. this.setState({
  15. country: response.data
  16. })
  17. })
  18. }
  19. Country() {
  20. return (this.state.country.map(data => ({ label: data.Name, value: data.Id })))
  21. }
  22. render() {
  23. return (
  24. <>
  25. <div style={{ margin: "10px" }} class="row" className="hdr">
  26. <div class="col-sm-12 btn btn-warning">
  27. React Select
  28. </div>
  29. </div>
  30. <div className="container">
  31. <div className="row">
  32. <div className="col-md-3"></div>
  33. <div className="col-md-6">
  34. <Select options={this.Country()} />
  35. </div>
  36. <div className="col-md-4"></div>
  37. </div>
  38. </div>
  39. </>
  40. )
  41. }
  42. }
  43. 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. const animatedComponents = makeAnimated();
  6. export class Multiselect extends Component {
  7. constructor(props) {
  8. super(props)
  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. Country() {
  22. return (this.state.country.map(data => ({ label: data.Name, value: data.Id })))
  23. }
  24. render() {
  25. return (
  26. <>
  27. <div style={{ margin: "10px" }} class="row" className="hdr">
  28. <div class="col-sm-12 btn btn-warning">
  29. React Select
  30. </div>
  31. </div>
  32. <div className="container">
  33. <div className="row">
  34. <div className="col-md-3"></div>
  35. <div className="col-md-6">
  36. <Select options={this.Country()} components={animatedComponents}
  37. isMulti />
  38. </div>
  39. <div className="col-md-4"></div>
  40. </div>
  41. </div>
  42. </>
  43. )
  44. }
  45. }
  46. 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. function App() {
  7. return (
  8. <div className="App">
  9. <Multiselect />
  10. </div>
  11. );
  12. }
  13. 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 = ON) ON [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.