Home > front end >  How to populate State dropdown data as per selected Country dropdown lists in React.js?
How to populate State dropdown data as per selected Country dropdown lists in React.js?

Time:09-23

I have two dropdowns first for country & second for state now, I want to populate the state dropdown based on the selected country.

Complete code url : https://codesandbox.io/s/nt54t6

This is my Code:-

import React, { useState, useEffect } from "react";
import "./styles.css";
import { TextField, MenuItem } from "@mui/material";


export default function App() {
  const body = [
    {
      state_ID: 1,
      state: "Delhi",
      country_ID: 1,
      country_name: "India"
    },
    {
      state_ID: 2,
      state: "Mumbai",
      country_ID: 1,
      country_name: "India"
    },
    {
      state_ID: 3,
      state: "Calgary",
      country_ID: 2,
      country_name: "Canada"
    },
    {
      state_ID: 4,
      state: "Toronto",
      country_ID: 2,
      country_name: "Canada"
    }
  ];
  const [country, setCountry] = useState([]);
  const [state, setState] = useState([]);

  const uniqValues = [
    ...new Map(body.map((item) => [item['country_name'], item])).values(),
];
  useEffect(()=>{
    setCountry(uniqValues);
    setState(body);
 },[])

  return (
        <>
          <TextField 
            className="ruleContainer" 
            select
            name="Country"
            label="Country"
            variant="outlined"
            size="small"
            // onChange={(event) =>
            //   handleChangeInput(inputField.id, event)
            // }
          >
            {country ?
               country.map((opt) => (
                 <MenuItem key={opt.country_name} value={opt.country_name}>
                   {opt.country_name}
                 </MenuItem>
               ))
               : ""}
          </TextField>              
          <TextField
            className="ruleContainer"
            select
            name="state"
            label="State"
            variant="outlined"
            size="small"
            value=""
            // onChange={(event) =>
            //   handleChangeInput(inputField.id, event)
            // }
           >
            {state? 
              state.map((opt) => (
                <MenuItem key={opt.state} value={opt.state}>
                  {opt.state}
                </MenuItem>
               ))
            : ""}
          </TextField>
        </>
        )
}

Thanks for your efforts!

CodePudding user response:

You will have to set values dynamically.

Steps:

  1. Create a variable to save selected country
const [selectedCountry, setSelectedCountry] = useState("");
  1. Create an onChange handler to update selected country
onChange={(event) => setSelectedCountry(event.target.value)}
  1. Create a useEffect on that so you can track changes
  2. In this, loop over body and filter out states valid for country. Set them to state
useEffect(() => {
  const newStates = body.filter(
    ({ country_name }) => country_name === selectedCountry
  );
  setState(newStates);
}, [selectedCountry]);

Updated Sandbox

  • Related