import "./styles.css";
import React, { useState } from "react";
export default function App() {
const statesAndCities = [
{ state: "Telangana", cities: ["Hyderabad", "Warangal"] },
{ state: "Madhya Pradesh", cities: ["Gwalior", "Bhopal"] },
{ state: "Rajasthan", cities: ["Jaipur", "Jaipur City"] },
{ state: "Chattisgarh", cities: ["Raipur", "ABC"] }
];
const [value, setvalue] = useState([]);
const [city, setcity] = useState([]);
const handleChange = (e) => {
setvalue(e.target.value);
setcity(statesAndCities.find((state) => state === e.target.value));
console.log(e.target.value);
};
return (
<div className="App">
<select onChange={handleChange}>
{statesAndCities.map((elem) => {
return <option value={elem.state}>{elem.state}</option>;
})}
</select>
<select onChange={handleChange}>
{statesAndCities.map((elem) => {
return <option value={elem.cities}>{elem.cities}</option>;
})}
</select>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
How we can filter cities on the bases of state selected in React. What logic do I need to write in handle change for display cities on the basis of states selected
2
Answers
You can try to do it this way:
And in your second select you can map through these cities:
You will also need to make state for your second select as well as a function for handling changes for this select (e.g. citiesOnChange). Additionaly, you should disable the second select if the user didn’t choose the value from the first select.
You would need
state
,cities
andselectedCity
.cities
will change whenever the user selects a differentstate
.selectedCity
will change whenever user selects a different city fromcities
state, but also whenever the user changesstate
for a better UI/UX design.Here’s how you can go about it: