DEV Community

 Subash.b
Subash.b

Posted on

Mastering Dependent Dropdowns: A React State Management Guide.

Today, I tackled a fun challenge by building a custom dependent drop down component in React. The goal was simple but powerful: based on a country selected in the first drop down, the second drop down dynamically updates to show only the relevant states, and the third filters cities accordingly.

To make this work, I structured my own mock data containing datasets for countries like India and the USA, complete with their respective states and cities. The core of the functionality relies on React state variables. I initialized separate states to capture the user's selections at each level.

When a user picks a country, the corresponding state list is populated, and once a state is chosen, the city options follow suit. By managing these variables effectively in the return statement, the UI smoothly reflects the hierarchical choices, storing each selection for further use. This project was a great way to understand how data flow and state synchronization work together to create an interactive user experience.

import { useState } from "react";

function Dropdown() {

    const data = {
India: {
TamilNadu: ["Chennai", "Coimbatore", "Madurai"],
Kerala: ["Kochi", "Trivandrum", "Kozhikode"]
},
USA: {
California: ["Los Angeles", "San Francisco"],
Texas: ["Houston", "Dallas"]
}
};

 const [Country, setcountry]  =  useState("")
 const [state, setState]  =  useState("")
 const [City, setCity]  =  useState("")
 function handelCountryChange(e) {
    setcountry(e.target.value);

 }
 function HandelStateChange(e) {
    setState(e.target.value);
 }
 function HandelCityChange(e) {
 }


    return(
        <div>
           <select name="" id="" onChange={handelCountryChange}>
           <option value="">Select Country</option>
           {
            Object.keys(data).map(( cntry )=>(
               <option value={cntry}>{cntry}</option>
            )) 
           }
           </select>

           <select name="" id="" onChange={HandelStateChange}>
           <option value="">Select State</option>
           {
            Country &&
            Object.keys(data[Country]).map(( State )=>(
               <option value={State}>{State}</option>
            )) 
           }
           </select>

           <select name="" id="" onChange={HandelCityChange}>
           <option value="">Select City</option>
           {
            state &&
            data[Country][state].map(( City )=>(
               <option value={City}>{City}</option>
            )) 
           }
           </select>

        </div>



    )
}
export default Dropdown



Enter fullscreen mode Exit fullscreen mode

Top comments (0)