Dynamic Dependent Dropdown in React JS

Dynamic Dependent Dropdown in React JS

cascading dropdown in react js; Through this tutorial, you will learn how to create a cascading dropdown or dependent country state city dropdown list in React JS using Web/REST APIS.

Cascading dropdowns in React JS is a powerful way to handle complex user input scenarios. It allows developers to create a hierarchical relationship between dropdown menus, where the options in the second dropdown are dependent on the selected value in the first dropdown.

For example, if a user selects a country in the first dropdown, the second dropdown menu will populate with the list of cities available in the selected country. This type of dynamic interaction between dropdowns makes the user experience more intuitive and streamlined, reducing the number of input errors and simplifying the overall user flow.

Cascading dropdowns in React JS can be implemented using a variety of techniques, such as state management libraries like Redux, or by using React hooks like useState and useEffect. Overall, cascading dropdowns are an essential tool for building sophisticated and responsive web applications in React JS.

In this populate dropdown based on another dropdown+react will show you how to create a dynamic cascading dependent country, state, city dropdown list using react js with the web apis.

Country State City Cascading Dependent Dropdown in React JS

Follow the below steps to implement dynamic cascading country state city dependent dropdown in react js using REST APIs:

  • Step 1 – Create React App
  • Step 2 – Install Axios and Bootstrap 4
  • Step 3 – Create Cascading Dropdown Component
  • Step 4 – Import Component in App.js
  • Step 5 – Add Css

Step 1 – Create React App

Open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app my-react-app

To run the React app, execute the following command on your terminal:

npm start

Check out your React app on this URL: localhost:3000

Step 2 – Install Axios and Bootstrap 4

Then execute the following command to install axios and boostrap 4 library into your react app:

npm install bootstrap --save

npm install axios --save

And import bootstrap.min.css file in src/App.js.

Step 3 – Create Cascading Dropdown Component

visit the src directory of your react js app and create a cascading dependent dropdown component; which is named Cascading.js. And add the following code into it:

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:3000/countries-list').then(response => {

            console.log(response.data);

            this.setState({

                CountryData: response.data
            });

        });

    }

    ChangeteState = (e) => {

        this.setState({
            CountryId: e.target.value
        });

        axios.get('http://localhost:3000/get-states-by-country?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/get-cities-by-state?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  

Here is a breakdown of the above given code:

  • The first line imports two things: the React library and the Component class from React.
  • The second line imports the axios library, which is used for making HTTP requests.
  • The third line imports the ReactHTMLTableToExcel library, which is used for exporting HTML tables to Excel.
  • The fourth line imports a CSS file for styling the app.
  • The next few lines define a class called CascadingDropdown, which extends the Component class from React. This class has a constructor function that initializes the state of the component with some empty arrays and strings.
  • The componentDidMount function is called when the component is first mounted on the page. In this function, an HTTP GET request is made to the URL http://localhost:3000/countries-list, which returns a list of countries. The response data is then set to the CountryData state variable using the setState function.
  • The ChangeteState and ChangeCity functions are called when the user selects a country and a state from the dropdown menus, respectively. These functions update the state of the component with the selected values and make HTTP GET requests to two different URLs. The response data is then set to the StateData or CityData state variables, respectively.
  • Finally, the render function is called to render the UI of the component. This function returns some HTML code that displays three dropdown menus for selecting a country, a state, and a city. The values of these dropdown menus are set to the state variables CountryId, StateId, and CityData, respectively. When the user selects a country or a state, the onChange event is triggered and calls the ChangeteState or ChangeCity function, respectively. The options of the dropdown menus are dynamically generated based on the data stored in the CountryData, StateData, and CityData state variables.

If you want to learn how to create country state city rest apis; So, You can checkout out how to create country state city rest api in node js express with MySQL database.

Step 4 – Import Component in App.js

import above created component like Cascading.js file in src/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; 

Step 5 – Add CSS

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

.dropdn  
{  
  margin-left: 250px;  
  margin-top: 20px;  
  margin-right: 250px;  
  padding: 30px;  
}  
.slct  
{  
  margin-top: 20px;  
} 

Conclusion

Cascading dropdown in react js; Through this tutorial, you have learned how to create a cascading dropdown or dependent country state city dropdown list in React JS using Web API.

Recommended React JS Tutorials

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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