I have data on server and two react-selects. This is my JSON data:
[{
"KIA": [
{
"id": 1,
"name": "Rio"
},
{
"id": 2,
"name": "Sorento"
},
{
"id": 3,
"name": "Stinger"
}
]
},{
"VOLKSWAGEN": [
{
"id": 4,
"name": "Polo"
},
{
"id": 5,
"name": "Golf"
},
{
"id": 6,
"name": "Tiguan"
},
]
}]
This is my first select where I fetched array of cars from the server and put it in state 'cars'. It worked, now I can choose brands.
<Select
options={
cars.map(c => (
{ value: Object.keys(c), label: Object.keys(c) }
))
}
/>
So here is what I want for second select:
If choose KIA brand in the first select --> I have 'Rio, Sorento, Stringer' options in the second select.
If choose VOLKSWAGEN brand in the first select --> I have 'Polo, Gold, Tiguan' options in the second select.
Is there a way to bind two selects to one piece of data where options of the second select depend on selected option in the first select? Ugh..
In the first select, start by initializing selected_sub_cats to [] in the state
<Select
options={
cars.map(c => (
{ value: Object.keys(c), label: Object.keys(c) }
))
}
onChange={(v)=>this.setState({selected: v, selected_sub_cats: cars.filter(car =>Object.keys(car) === v)})}
/>
Then in the second select
<Select
options={this.state.selected_sub_cars}
onChange={(v)=>this.setState({selected_sub: v, })}
/>
This chunk of code is a lot inaccurate, you ll have to format the data and debug since I didn't run it. It's just to give you a gist regarding the logic :
const dataSet = [{
"KIA": [
{
"id": 1,
"name": "Rio"
},
{
"id": 2,
"name": "Sorento"
},
{
"id": 3,
"name": "Stinger"
}
]
},{
"VOLKSWAGEN": [
{
"id": 4,
"name": "Polo"
},
{
"id": 5,
"name": "Golf"
},
{
"id": 6,
"name": "Tiguan"
},
]
}]
Component starts here:
const [ selectedBrand, setSelectedBrand ] = useState()
const [ selectedModel, setSelectedModel ] = useState()
const [ brandOptions, setBrandOptions ] = useState(Object.keys(dataSet))
const [ modelOptions, setModelOptions ] = useState()
// Based on the brand you select, the useEffect should set the relevant options for the models
useEffect(()=>{
setModelOptions(brandOptions[selectedBrand])
},[selectedBrand])
function handleChangeBrand(brand){
setSelectedBrand(brand)
}
function handleChangeModel(model){
setSelectedModel(model)
}
return (
<Select
value={selectedBrand}
onChange={(value) => handleChangeBrand(value)}
options={brandOptions}
/>
<Select
value={selectedModel}
onChange={(value) => handleChangeModel(value)}
options={modelOptions}
/>