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
- USE [CascadingDemo]
- GO
- /****** Object: Table [dbo].[City] Script Date: 1/11/2020 5:56:32 PM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE TABLE [dbo].[City](
- [CityId] [int] IDENTITY(1,1) NOT NULL,
- [cityName] [varchar](50) NULL,
- [StateId] [int] NULL,
- CONSTRAINT [PK_City] PRIMARY KEY CLUSTERED
- (
- [CityId] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- /****** Object: Table [dbo].[Country] Script Date: 1/11/2020 5:56:33 PM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE TABLE [dbo].[Country](
- [CountryId] [int] IDENTITY(1,1) NOT NULL,
- [CountryName] [varchar](50) NULL,
- PRIMARY KEY CLUSTERED
- (
- [CountryId] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- /****** Object: Table [dbo].[State] Script Date: 1/11/2020 5:56:33 PM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE TABLE [dbo].[State](
- [StateId] [int] IDENTITY(1,1) NOT NULL,
- [StateName] [varchar](50) NULL,
- [CountryId] [int] NULL,
- CONSTRAINT [PK_State] PRIMARY KEY CLUSTERED
- (
- [StateId] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- SET IDENTITY_INSERT [dbo].[City] ON
-
- INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (1, N'Jaipur', 1)
- INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (2, N'Jodhpur', 1)
- INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (3, N'Noida', 4)
- INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (4, N'Greater Noida', 4)
- INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (5, N'Surat', 3)
- INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (6, N'Vapi', 3)
- INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (7, N'Mohali', 2)
- INSERT [dbo].[City] ([CityId], [cityName], [StateId]) VALUES (8, N'Chandigarh', 2)
- SET IDENTITY_INSERT [dbo].[City] OFF
- SET IDENTITY_INSERT [dbo].[Country] ON
-
- INSERT [dbo].[Country] ([CountryId], [CountryName]) VALUES (1, N'INDIA')
- INSERT [dbo].[Country] ([CountryId], [CountryName]) VALUES (2, N'AUSTRALIA')
- INSERT [dbo].[Country] ([CountryId], [CountryName]) VALUES (3, N'USA')
- SET IDENTITY_INSERT [dbo].[Country] OFF
- SET IDENTITY_INSERT [dbo].[State] ON
-
- INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (1, N'Rajasthan', 1)
- INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (2, N'Punjab', 1)
- INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (3, N'Gujrat', 1)
- INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (4, N'UttarPradesh', 1)
- INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (5, N'New South Wales', 2)
- INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (6, N'Queensland', 2)
- INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (7, N'South Australia', 2)
- INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (8, N'Tasmania', 2)
- INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (9, N'Alabama', 3)
- INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (10, N'California', 3)
- INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (11, N'Idaho', 3)
- INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (12, N'Louisiana', 3)
- SET IDENTITY_INSERT [dbo].[State] OFF
Create a new Web API project
Open Visual Studio and create a new project.
Change the name to CascadingDemo.
Choose the template as Web API.
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
Click on the "ADO.NET Entity Data Model" option and click "Add".
Select EF Designer from the database and click the "Next" button.
Add the connection properties and select database name on the next page and click OK.
Check the "Table" checkbox. The internal options will be selected by default. Now, click OK
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.
- using CascadingDemo.Models;
Now add three methods to get country, state, and city data from the database.
- [Route("Country")]
- [HttpGet]
- public object GetCountry()
- {
- return DB.Countries.ToList();
- }
- [Route("State")]
- [HttpGet]
- public object GetState(int CountryId)
- {
- return DB.States.Where(s => s.CountryId == CountryId).ToList();
- }
- [Route("city")]
- [HttpGet]
- public object GetCity(int StateId)
- {
- return DB.Cities.Where(s => s.StateId == StateId).ToList();
- }
Complete CascadingDemo controller code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using CascadingDemo.Models;
-
- namespace CascadingDemo.Controllers
- {
- [RoutePrefix("Api/cascading")]
- public class CascadingController : ApiController
- {
- CascadingDemoEntities DB = new CascadingDemoEntities();
- [Route("Country")]
- [HttpGet]
- public object GetCountry()
- {
- return DB.Countries.ToList();
- }
- [Route("State")]
- [HttpGet]
- public object GetState(int CountryId)
- {
- return DB.States.Where(s => s.CountryId == CountryId).ToList();
- }
- [Route("city")]
- [HttpGet]
- public object GetCity(int StateId)
- {
- return DB.Cities.Where(s => s.StateId == StateId).ToList();
- }
- }
- }
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.
- EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
- config.EnableCors(cors);
Create ReactJS project
Now, let's first create a React application with the following command.
- npx create-react-app matform
Now install Bootstrap by using the following commands.
- npm install --save bootstrap
Now, open the index.js file and add import Bootstrap.
- import 'bootstrap/dist/css/bootstrap.min.css';
Now install the Axios library by using the following command. Learn more about
Axios
Now go to the src folder and add a new component, named 'Cascading.js'. and add the following code.
- import React, { Component } from 'react'
- import axios from 'axios';
- import ReactHTMLTableToExcel from 'react-html-table-to-excel';
- import './App.css';
- export class CascadingDropdown extends Component {
- constructor(props) {
- super(props)
- this.state = {
- StateId:'',
- CountryId: '',
- CountryData: [],
- StateData: [],
- CityData: []
- }
- }
- componentDidMount() {
- axios.get('http://localhost:65173/Api/cascading/Country').then(response => {
- console.log(response.data);
- this.setState({
- CountryData: response.data
- });
- });
- }
- ChangeteState = (e) => {
- this.setState({ CountryId: e.target.value });
- axios.get('http://localhost:65173/Api/cascading/State?CountryId=' +e.target.value ).then(response => {
- console.log(response.data);
- this.setState({
- StateData: response.data,
- });
- });
- }
- ChangeCity = (e) => {
- this.setState({ StateId: e.target.value });
- axios.get('http://localhost:65173/Api/cascading/city?StateId=' + e.target.value).then(response => {
- console.log(response.data);
- this.setState({
- CityData: response.data
- });
- });
- }
- render() {
- return (
- <div>
- <div class="row" className="hdr">
- <div class="col-sm-12 btn btn-info">
- Cascading Dropdown in ReactJS
- </div>
- </div>
- <div className="form-group dropdn">
- <select className="form-control" name="country" value={this.state.CountryId} onChange={this.ChangeteState} >
- <option>Select Country</option>
- {this.state.CountryData.map((e, key) => {
- return <option key={key} value={e.CountryId}>{e.CountryName}</option>;
- })}
- </select>
- <select className="form-control slct" name="state" value={this.state.StateId} onChange={this.ChangeCity} >
- <label for="company">State Name</label>
- {this.state.StateData.map((e, key) => {
- return <option key={key} value={e.StateId}>{e.StateName}</option>;
- })}
- </select>
- <select className="form-control slct" name="city" value={this.state.CityData} >
-
- {this.state.CityData.map((e, key) => {
- return <option key={key} value={e.CityId}>{e.cityName}</option>;
- })}
- </select>
- </div>
- </div>
- )
- }
- }
-
- export default CascadingDropdown
Add a reference of this component in app.js file, add the following code in app.js file.
- import React from 'react';
- import logo from './logo.svg';
- import './App.css';
- import CascadingDropdown from './Cascading'
-
- function App() {
- return (
- <div className="App">
- <CascadingDropdown/>
- </div>
- );
- }
-
- export default App;
Now open app.css file , add the following css classes
- .dropdn
- {
- margin-left: 250px;
- margin-top: 20px;
- margin-right: 250px;
- padding: 30px;
- }
- .slct
- {
- margin-top: 20px;
- }
Now run the project and select country value from country dropdown, based on country state dropdown filled in.
Now based on state and its city in city dropdown.
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.