Parent – Child Dropdown Selectboxes in React Example – Interdependent Selection Tutorial

In this React tutorial, we will explore how to add a select box or dropdown form control and bind on change event handler onto it. We will be discussing adding multiple react dropdowns having interdependency for its child dropdown.

If you looking at how to add a select box control in a React Js application, then you are in the right place. Adding a simple form control like a select box is very easy in a React JS application. The onChange event handler will emit the value of dropdown, which we can fetch on submit of form event.

In our example, we will have three dropdowns showing countries, states and cities, these will be in the cascading arrangement. The country dropdown will be parent of states and states will be parent of cities dropdown, having values dependent of previous selected value.

Creating Multiple Hararical Dropdowns in React App

  • Step 1 – Setup React App
  • Step 2 – Install Bootstrap Library
  • Step 3 – Create Dropdown Component
  • Step 4 – Using Dropdowns in App
  • Step 5 – Run React App

 

Step 1 – Setup React App

First, create a new react app by executing the below npx command by providing a name you like.

npx create-react-app react-dropdown-app

Move into the application directory by executing the change directory command:

cd react-dropdown-app

Step 2 – Install Bootstrap Library

To style the react app quickly, let’s install the bootstrap package to use its css file and use bootstrap classes:

npm install bootstrap --save

Step 3 – Create Dropdown Component

Now head towards the src/component folder at the app root and create a new file countryDropdown.js containing the countryDropdown class:

import React, { Component } from "react";

const countriesData = require("../data/countries.json");
const statesData = require("../data/states.json");
const citiesData = require("../data/cities.json");

export class CountryDropdown extends Component {
  constructor(props) {
    super(props);
    this.state = {
      StateId: "",
      CountryId: "",
      CityId: "",
      CountryData: [],
      StateData: [],
      CityData: [],
    };
  }

  componentDidMount() {
    this.setState({
      CountryData: countriesData,
    });
  }

  OnCountryChange = (e) => {
    const filteredStates = statesData.filter((state) => {
      return state.country_id == e.target.value;
    });
    this.setState({
      CountryId: e.target.value,
      StateId: "",
      CityId: "",
      StateData: filteredStates,
      CityData: [],
    });
  };

  OnStateChange = (e) => {
    const filteredCities = citiesData.filter((city) => {
      return (
        city.country_id == this.state.CountryId &&
        city.state_id == e.target.value
      );
    });
    this.setState({
      StateId: e.target.value,
      CityId: "",
      CityData: filteredCities,
    });
  };

  OnCityChange = (e) => {
    this.setState({
      CityId: e.target.value,
    });
  };

  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col-12">
            <h5>Parent - Child Dropdowns in ReactJS</h5>
          </div>
        </div>
        <div className="row">
          <div className="col-4">
            <select
              className="form-control"
              name="country"
              value={this.state.CountryId}
              onChange={(e) => this.OnCountryChange(e)}
            >
              <option value>Select Country</option>
              {this.state.CountryData.map((e, key) => {
                return (
                  <option key={key} value={e.id}>
                    {e.name}
                  </option>
                );
              })}
            </select>
          </div>
          <div className="col-4">
            <select
              className="form-control"
              name="state"
              value={this.state.StateId}
              onChange={(e) => this.OnStateChange(e)}
            >
              <option value>State Name</option>
              {this.state.StateData.map((e, key) => {
                return (
                  <option key={key} value={e.id}>
                    {e.name}
                  </option>
                );
              })}
            </select>
          </div>
          <div className="col-4">
            <select
              className="form-control"
              name="city"
              value={this.state.CityId}
              onChange={(e) => this.OnCityChange(e)}
            >
              <option value>Select City</option>
              {this.state.CityData.map((e, key) => {
                return (
                  <option key={key} value={e.id}>
                    {e.name}
                  </option>
                );
              })}
            </select>
          </div>
        </div>
      </div>
    );
  }
}
export default CountryDropdown;

We have three dropdowns for the country, state and cities with its state maintained as well. We are getting the JSON data from a local file placed inside the data folder. you can also fetch these values from a remote server using Axios or simple fetch Javascript calls.

We have got the data for countries, states and cities from countrystatecity.in. You can easily get an API key to use the already available JSON data objects.

You can directly download the countries, states or cities JSON data from a direct URL and place it on your servers.

Step 4 – Using Dropdowns in App

Now open the App.js file and update it to use the CountryDropdown component and also import the bootstrap.min.css file as shown below:

import React from "react";
import "./App.css";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import CountryDropdown from "./components/countryDropdown";

function App() {
  return (
    <div className="App">
      <CountryDropdown />
    </div>
  );
}

export default App;

Step 5 – Run React App

Finally, execute the react app to see the implementation in action. Run following command in the terminal window:

npm start

It will start the webserver and open the react at following URL:

http://localhost:3000

Conclusion

We have demonstrated how to create dropdowns with parent and child relations. The selection of country, state and city are done based on the previous selection. Each child is having the id of its parent selection so it gets filtered out on parents selection.

Leave a Reply

Your email address will not be published. Required fields are marked *