Click here to Skip to main content
15,887,485 members
Articles / Programming Languages / SQL
Tip/Trick

Cascading Dropdown In ReactJS

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
1 Mar 2020CPOL2 min read 15.4K   2  
How to create a cascading dropdown using ReactJS and Web API
This tip will show how to create cascading dropdowns using ReactJS and Web API. Child dropdown values are populated based on the item selected in the parent dropdown.

Introduction

In this tip, 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

  • 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 three tables and some demo data in the tables:

  1. Country
  2. State
  3. City
SQL
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.

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

C#
using CascadingDemo.Models;

Now, add three methods to get country, state, and city data from the database.

JavaScript
[Route("Country")]
   [HttpGet]
   public object GetCountry()
   {
       return  DB.Countries.ToList();
   }
JavaScript
[Route("State")]
   [HttpGet]
   public object GetState(int CountryId)
   {
       return DB.States.Where(s => s.CountryId == CountryId).ToList();
   }
JavaScript
[Route("city")]
    [HttpGet]
    public object GetCity(int StateId)
    {
        return DB.Cities.Where(s => s.StateId == StateId).ToList();
    }

Complete CascadingDemo Controller Code

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

JavaScript
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.

JavaScript
import 'bootstrap/dist/css/bootstrap.min.css';

Now install the Axios library by using the following command. Learn more about Axios:

npm install --save axios

Now go to the src folder and add a new component, named 'Cascading.js'. and add the following code:

JavaScript
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 (

Cascading Dropdown in ReactJS

SQL
Select Country {this.state.CountryData.map((e, key) => { return{e.CountryName}; })} 
State Name {this.state.StateData.map((e, key) => 
{ return{e.StateName}; })} {this.state.CityData.map((e, key) => { return{e.cityName}; })}

) } } export default CascadingDropdown

Add a reference of this component in app.js file, add the following code in app.js file.

JavaScript
import React from 'react';  
import logo from './logo.svg';  
import './App.css';  
import CascadingDropdown from './Cascading'  
  
function App() {  
  return (     

<cascadingdropdown>

); } export default App;

Now open app.css file, add the following CSS classes:

CSS
    .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.

Create Cascading Dropdown In ReactJS

Now based on state and its city in city dropdown.

Create Cascading Dropdown In ReactJS

Summary

In this post, 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.

History

  • 2nd March, 2020: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
-- There are no messages in this forum --