We can make dropdowns in React JS by following method :
Step 1 : Take a list of states and cities object related to every state or we can get this data using apis.
Step 2 : Loop over the states data to show dropdown related to All States.
Step 3 : Now save the selected state.
Step 4 : Based on selected state value , get the corresponding cities and show them in dropdown as follows :
In App.js
import { useState } from "react";
import './App.css';
function App() {
const states = ['UP', 'Delhi', 'Gujrat']
const cities = {
'UP': ['f', 'g', 'l'],
'Delhi': ['a', 'b'],
'Gujrat': ['tr', 'trt', 'rtt'],
}
const [selectedState, setSelectedState] = useState('')
console.log(selectedState)
return (
<div>
CASCADING DROPDOWNS :
<select onChange={(e) => { setSelectedState(e.target.value) }}>
{
states.map(state => {
return <option>{state}</option>
})
}
</select>
{selectedState && <select>
{
cities[selectedState].map(city => {
return <option>{city}</option>
})
}
</select>}
</div>
);
}
export default App;
In App.css (optional)
select{
width: 150px;
margin : 20px;
}
Comments
Post a Comment