Made with function Component
The state dropdown value automatically changes on changing the country value
Data from country to state component is passed using simple props
App.js :
import logo from "./logo.svg";
import "./App.css";
import Country from "./Country";
function App() {
return (
<div className="App">
<Country />
</div>
);
}
export default App;
Country.jsx
import React, { useState } from "react";
import States from "./States";
const Country = () => {
const [country, setCountry] = useState();
const countryData = [
{ key: "India", value: "India" },
{ key: "USA", value: "USA" },
{ key: "Pakistan", value: "Pakistan" },
];
return (
<>
<div className="country">
<h3>Choose Country</h3>
<select
id="country"
value={country}
onChange={(e) => setCountry(e.target.value)}
>
{/* <option>--select--</option> */}
{countryData.map((c, i) => (
<option key={i} value={c.value}>
{c.value}
</option>
))}
</select>
</div>
<States country={country} />
</>
);
};
export default Country;
State.jsx
import React, { useState } from "react";
const State = ({ country }) => {
// const [states, setStates] = useState();
console.log("country from state", country);
function showStateData(country) {
if (country === "India") {
return (
<>
<option value="Delhi">Delhi </option>
<option value="Mumbai">Mumbai </option>
<option value="Delhi">Kolkata </option>
</>
);
} else if (country === "USA") {
return (
<>
<option value="New York">New York </option>
<option value="Allanta">Allanta </option>
<option value="Washington">Washington </option>
</>
);
} else if (country === "Pakistan") {
return (
<>
<option value="Balochistan">Balochistan</option>
<option value="Amarkot">Amarkot</option>
<option value="Karanchu">Karanchi </option>
</>
);
}
}
return (
<>
<div className="country">
<h3>Choose State</h3>
<select id="country" value="country">
{/* <option>--select--</option> */}
{country && showStateData(country)}
</select>
</div>
</>
);
};
export default State;
The End.
0 Comments