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:
- Create a variable to save selected country
const [selectedCountry, setSelectedCountry] = useState("");
- Create an
onChange
handler to update selected country
onChange={(event) => setSelectedCountry(event.target.value)}
- Create a
useEffect
on that so you can track changes - 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]);