Introduction

In this post we will see an example on cascading or dependent dropdown using React JS. When you have a requirement for selecting dropdown values based on another dropdown values then you need to create such cascading or dependent dropdown. For example, in your application you need to select city based on state or country then you need to create such dependent dropdown.

Here we will create some dummy dataset for country, state and city and we will show in the dropdown with select/option tags.

The first dropdown will contain country names, the second dropdown will show state names based on the country name and finally third dropdown will show city names based on the state name from the second dropdown.

Prerequisites

Node v12.9.1, Npm 6.10.2, React JS, Windows 10 64 bit

Example

We will show you an example on cascading or dependent dropdown with select options for Country -> State -> City. So when you select Country you will corresponding States and when you select State you will get corresponding Cities.

Final Results

You will see the below page on the browser for the home page, where you will see three cascading dropdown as shown in the below image:

cascading or dependent dropdown using react js

Selecting country dropdown’s value you will get state populated and selecting state dropdown value you will get city dropdown populated.

cascading or dependent dropdown using react js

Create React Application

You may go through the tutorial how to create React application in Windows. The name of the application is react-dependent-dropdown.

Create Cascaded or Dependent Dropdowns

Now we will write the required code using React JS to build the cascaded or dependent dropdowns.

Generally we will write our code in JS files inside src directory under project root directory.

index.js

This file is the root file and it defines all paths or loads the file required to navigate once your application functionality is displayed on ReactJS UI.

In the below source code of index.js file we have imported Dropdown which we will later define to create the dropdown functionality.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Dropdown from './Dropdown';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<Dropdown />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
//serviceWorker.unregister();
serviceWorker.register();

Dropdown.js

Now we will create a file called Dropdown.js in the src folder for implementing the dependent dropdown functionalities.

You can read about componentDidMount().

In the constructor we have declared few variables, such as countries, states, cities with empty arrays.

Inside the componentDidMount() function, we catch the click event from the dropdown and accordingly we populate the child dropdown.

Inside the render() function we build the select/option tags to display the dropdowns and bind the UI events.

import React from 'react';

class Dropdown extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			countries : [],
			states : [],
			cities : [],
			selectedCountry : '--Choose Country--',
			selectedState : '--Choose State--'
		};
		this.changeCountry = this.changeCountry.bind(this);
		this.changeState = this.changeState.bind(this);
	}
  
	componentDidMount() {
		this.setState({
			countries : [
				{ name: 'Germany', states: [ {name: 'A', cities: ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn']} ] },
				{ name: 'Spain', states: [ {name: 'B', cities: ['Barcelona']} ] },
				{ name: 'USA', states: [ {name: 'C', cities: ['Downers Grove']} ] },
				{ name: 'Mexico', states: [ {name: 'D', cities: ['Puebla']} ] },
				{ name: 'India', states: [ {name: 'E', cities: ['Delhi', 'Kolkata', 'Mumbai', 'Bangalore']} ] },
			]
		});
	}
  
	changeCountry(event) {
		this.setState({selectedCountry: event.target.value});
		this.setState({states : this.state.countries.find(cntry => cntry.name === event.target.value).states});
	}

	changeState(event) {
		this.setState({selectedState: event.target.value});
		const stats = this.state.countries.find(cntry => cntry.name === this.state.selectedCountry).states;
		this.setState({cities : stats.find(stat => stat.name === event.target.value).cities});
	}
	
	render() {
		return (
			<div id="container">
				<h2>Cascading or Dependent Dropdown using React</h2>
	
				<div>
					<label>Country</label>
					<select placeholder="Country" value={this.state.selectedCountry} onChange={this.changeCountry}>
						<option>--Choose Country--</option>
						{this.state.countries.map((e, key) => {
							return <option key={key}>{e.name}</option>;
						})}
					</select>
				</div>

				<div>
					<label>State</label>
					<select placeholder="State" value={this.state.selectedState} onChange={this.changeState}>
						<option>--Choose State--</option>
						{this.state.states.map((e, key) => {
							return <option key={key}>{e.name}</option>;
						})}
					</select>
				</div>
				
				<div>
					<label>City</label>
					<select placeholder="City">
						<option>--Choose City--</option>
						{this.state.cities.map((e, key) => {
							return <option key={key}>{e}</option>;
						})}
					</select>
				</div>
			</div>
		)
	}
}

export default Dropdown;

That’s all.

Source Code

Download

Thanks for reading.

Tags:

1 thought on “Cascading or dependent dropdown using React JS

  1. This is a very common case where developers get stuck in any language or framework. I remember I had faced this issue while making my college project in AI with PHP and I had to make a student form in which I needed to include this country, city and state things. I know I was irritated and confused because at that time developing code was a tedious task for me. But, right now I guess it’s easy.

    Well, your article would be very helpful for students and developers. Off to share. Thanks for posting.

Comments are closed.