Create Cascading Dropdown In ReactJS

Introduction

 
In this article, we will learn how to create a cascading dropdown using ReactJS and Web API. Cascading dropdown is a group of dropdowns where the value of one dropdown depends upon another dropdown value. Child dropdown values are populated based on the item selected in the parent dropdown.
 
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 and HTML

Create a table in the database

 
Open SQL Server Management Studio, create a database named "CascadingDemo", and in this database, create 3 tables and some demo data in the tables
  1. Country
  2. State
  3. City 
  1. USE [CascadingDemo]  
  2. GO  
  3. /****** Object:  Table [dbo].[City]    Script Date: 1/11/2020 5:56:32 PM ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. CREATE TABLE [dbo].[City](  
  9.     [CityId] [int] IDENTITY(1,1) NOT NULL,  
  10.     [cityName] [varchar](50) NULL,  
  11.     [StateId] [intNULL,  
  12.  CONSTRAINT [PK_City] PRIMARY KEY CLUSTERED   
  13. (  
  14.     [CityId] ASC  
  15. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  16. ON [PRIMARY]  
  17. GO  
  18. /****** Object:  Table [dbo].[Country]    Script Date: 1/11/2020 5:56:33 PM ******/  
  19. SET ANSI_NULLS ON  
  20. GO  
  21. SET QUOTED_IDENTIFIER ON  
  22. GO  
  23. CREATE TABLE [dbo].[Country](  
  24.     [CountryId] [int] IDENTITY(1,1) NOT NULL,  
  25.     [CountryName] [varchar](50) NULL,  
  26. PRIMARY KEY CLUSTERED   
  27. (  
  28.     [CountryId] ASC  
  29. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  30. ON [PRIMARY]  
  31. GO  
  32. /****** Object:  Table [dbo].[State]    Script Date: 1/11/2020 5:56:33 PM ******/  
  33. SET ANSI_NULLS ON  
  34. GO  
  35. SET QUOTED_IDENTIFIER ON  
  36. GO  
  37. CREATE TABLE [dbo].[State](  
  38.     [StateId] [int] IDENTITY(1,1) NOT NULL,  
  39.     [StateName] [varchar](50) NULL,  
  40.     [CountryId] [intNULL,  
  41.  CONSTRAINT [PK_State] PRIMARY KEY CLUSTERED   
  42. (  
  43.     [StateId] ASC  
  44. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  45. ON [PRIMARY]  
  46. GO  
  47. SET IDENTITY_INSERT [dbo].[City] ON   
  48.   
  49. INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (1, N'Jaipur', 1)  
  50. INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (2, N'Jodhpur', 1)  
  51. INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (3, N'Noida', 4)  
  52. INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (4, N'Greater Noida', 4)  
  53. INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (5, N'Surat', 3)  
  54. INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (6, N'Vapi', 3)  
  55. INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (7, N'Mohali', 2)  
  56. INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (8, N'Chandigarh', 2)  
  57. SET IDENTITY_INSERT [dbo].[City] OFF  
  58. SET IDENTITY_INSERT [dbo].[Country] ON   
  59.   
  60. INSERT [dbo].[Country] ([CountryId], [CountryName]) VALUES (1, N'INDIA')  
  61. INSERT [dbo].[Country] ([CountryId], [CountryName]) VALUES (2, N'AUSTRALIA')  
  62. INSERT [dbo].[Country] ([CountryId], [CountryName]) VALUES (3, N'USA')  
  63. SET IDENTITY_INSERT [dbo].[Country] OFF  
  64. SET IDENTITY_INSERT [dbo].[State] ON   
  65.   
  66. INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (1, N'Rajasthan', 1)  
  67. INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (2, N'Punjab', 1)  
  68. INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (3, N'Gujrat', 1)  
  69. INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (4, N'UttarPradesh', 1)  
  70. INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (5, N'New South Wales', 2)  
  71. INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (6, N'Queensland', 2)  
  72. INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (7, N'South Australia', 2)  
  73. INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (8, N'Tasmania', 2)  
  74. INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (9, N'Alabama', 3)  
  75. INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (10, N'California', 3)  
  76. INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (11, N'Idaho', 3)  
  77. INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (12, N'Louisiana', 3)  
  78. SET IDENTITY_INSERT [dbo].[State] OFF  

Create a new Web API project

 
Open Visual Studio and create a new project.
 
Create Cascading Dropdown In ReactJS
 
Change the name to CascadingDemo. 
 
Create Cascading Dropdown In ReactJS
 
Choose the template as Web API. 
 
Create Cascading Dropdown In ReactJS
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
Create Cascading Dropdown In ReactJS
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
Create Cascading Dropdown In ReactJS
 
Select EF Designer from the database and click the "Next" button.
 
Create Cascading Dropdown In ReactJS
 
Add the connection properties and select database name on the next page and click OK.
 
Create Cascading Dropdown In ReactJS
 
Check the "Table" checkbox. The internal options will be selected by default. Now, click OK
 
Create Cascading Dropdown In ReactJS
 
Now, our data model is successfully created.
 
Right-click on the Controllers folder and add a new controller. Name it as "CascadingDemo controller" and add the following namespace in the CascadingDemo controller.
  1. using CascadingDemo.Models;  
Now add three methods to get country, state, and city data from the database.
  1. [Route("Country")]  
  2.        [HttpGet]  
  3.        public object GetCountry()  
  4.        {  
  5.            return  DB.Countries.ToList();  
  6.        }  
  1. [Route("State")]  
  2.        [HttpGet]  
  3.        public object GetState(int CountryId)  
  4.        {  
  5.            return DB.States.Where(s => s.CountryId == CountryId).ToList();  
  6.        }  
  1. [Route("city")]  
  2.         [HttpGet]  
  3.         public object GetCity(int StateId)  
  4.         {  
  5.             return DB.Cities.Where(s => s.StateId == StateId).ToList();  
  6.         }  
Complete CascadingDemo 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 CascadingDemo.Models;  
  8.   
  9. namespace CascadingDemo.Controllers  
  10. {  
  11.     [RoutePrefix("Api/cascading")]  
  12.     public class CascadingController : ApiController  
  13.     {  
  14.         CascadingDemoEntities DB = new CascadingDemoEntities();  
  15.         [Route("Country")]  
  16.         [HttpGet]  
  17.         public object GetCountry()  
  18.         {  
  19.             return  DB.Countries.ToList();  
  20.         }  
  21.         [Route("State")]  
  22.         [HttpGet]  
  23.         public object GetState(int CountryId)  
  24.         {  
  25.             return DB.States.Where(s => s.CountryId == CountryId).ToList();  
  26.         }  
  27.         [Route("city")]  
  28.         [HttpGet]  
  29.         public object GetCity(int StateId)  
  30.         {  
  31.             return DB.Cities.Where(s => s.StateId == StateId).ToList();  
  32.         }  
  33.     }  
  34. }  
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);  

Create ReactJS project

 
Now, let's first create a React application with the following command.
  1. npx create-react-app matform   
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 'Cascading.js'. and add the following code.
  1. import React, { Component } from 'react'  
  2. import axios from 'axios';  
  3. import ReactHTMLTableToExcel from 'react-html-table-to-excel';  
  4. import './App.css';  
  5. export class CascadingDropdown extends Component {  
  6.         constructor(props) {  
  7.                 super(props)  
  8.                 this.state = {  
  9.                         StateId:'',  
  10.                         CountryId: '',  
  11.                         CountryData: [],  
  12.                         StateData: [],  
  13.                         CityData: []  
  14.                 }  
  15.         }  
  16.         componentDidMount() {  
  17.                 axios.get('http://localhost:65173/Api/cascading/Country').then(response => {  
  18.                         console.log(response.data);  
  19.                         this.setState({  
  20.                                 CountryData: response.data  
  21.                         });  
  22.                 });  
  23.         }  
  24.         ChangeteState = (e) => {  
  25.                 this.setState({ CountryId: e.target.value });  
  26.                 axios.get('http://localhost:65173/Api/cascading/State?CountryId=' +e.target.value ).then(response => {  
  27.                         console.log(response.data);  
  28.                         this.setState({  
  29.                                 StateData: response.data,  
  30.                         });  
  31.                 });  
  32.         }  
  33.         ChangeCity = (e) => {  
  34.                 this.setState({ StateId: e.target.value });  
  35.                 axios.get('http://localhost:65173/Api/cascading/city?StateId=' + e.target.value).then(response => {  
  36.                         console.log(response.data);  
  37.                         this.setState({  
  38.                                 CityData: response.data  
  39.                         });  
  40.                 });  
  41.         }  
  42.         render() {  
  43.                 return (  
  44.                         <div>  
  45.                                 <div class="row" className="hdr">  
  46.                                         <div class="col-sm-12 btn btn-info">  
  47.                                                 Cascading Dropdown in ReactJS  
  48.                             </div>  
  49.                                 </div>  
  50.                                 <div className="form-group dropdn">  
  51.                                         <select className="form-control" name="country" value={this.state.CountryId} onChange={this.ChangeteState}  >  
  52.                                                 <option>Select Country</option>  
  53.                                                 {this.state.CountryData.map((e, key) => {  
  54.                                                         return <option key={key} value={e.CountryId}>{e.CountryName}</option>;  
  55.                                                 })}  
  56.                                         </select>  
  57.                                         <select className="form-control slct" name="state" value={this.state.StateId} onChange={this.ChangeCity} >  
  58.                                         <label for="company">State Name</label>    
  59.                                                 {this.state.StateData.map((e, key) => {  
  60.                                                         return <option key={key} value={e.StateId}>{e.StateName}</option>;  
  61.                                                 })}  
  62.                                         </select>  
  63.                                         <select className="form-control slct" name="city" value={this.state.CityData}  >  
  64.                                           
  65.                                                 {this.state.CityData.map((e, key) => {  
  66.                                                         return <option key={key} value={e.CityId}>{e.cityName}</option>;  
  67.                                                 })}  
  68.                                         </select>  
  69.                                 </div>  
  70.                       </div>  
  71.                 )  
  72.         }  
  73. }  
  74.   
  75. export default CascadingDropdown  
 Add a reference of this component in app.js file, add the following code in app.js file.
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import CascadingDropdown from './Cascading'  
  5.   
  6. function App() {  
  7.   return (  
  8.     <div className="App">  
  9.       <CascadingDropdown/>  
  10.     </div>  
  11.   );  
  12. }  
  13.   
  14. export default App;  
Now open app.css file , add the following css classes
  1. .dropdn  
  2. {  
  3.   margin-left: 250px;  
  4.   margin-top: 20px;  
  5.   margin-right: 250px;  
  6.   padding: 30px;  
  7. }  
  8. .slct  
  9. {  
  10.   margin-top: 20px;  
  11. }  
Now run the project and select country value from country dropdown, based on country state dropdown filled in.
 
Create Cascading Dropdown In ReactJS
 
Now based on state and its city in city dropdown.
 
Create Cascading Dropdown In ReactJS
 

Summary

 
In this article, we learned how to create cascading dropdowns using ReactJS and Web API. Child dropdown values are populated based on the item selected in the parent dropdown.