I have a code as below in which am trying to implement dropdown cascading:-
import React, { Component } from 'react';
import { useHistory } from "react-router-dom";
class clusterServersDropdown extends Component {
constructor(){
super();
this.state = {
clusterslist:[],
servertype:[],
selectcluster:'',
};
}
componentDidMount(){
this.setState({
clusterslist:[
{label: "cluster1", servertype:["test1","test2","test3"]},
{label: "cluster2", servertype:["test1","test2","test3"]},
]
});
}
selectclusterChange(e){
this.setState({selectcluster:e.target.value});
this.setState({servertype: this.state.clusterslist.find(x => x.label===e.target.value).servertype })
}
routeChange = (e) => {
console.log(this.state.selectcluster)
console.log(this.state.servertype)
};
render(){
return(
<div>
<center>
<h1>
Implement cascading Dropdown list
<h2>
ReactJS tutorials
<hr />
<select value={this.state.selectcluster} onChange={this.selectclusterChange.bind(this)}>
<option>
-- Select --
</option>
{this.state.clusterslist.map(x => {
return <option>
{x.label}
</option>
})}
</select>
<select value={this.state.servertype} onChange={this.routeChange}>
<option>
--------selection disabled------
</option>
{
this.state.servertype.map(
x => {
return <option>
{x}
</option>
}
)
}
</select>
</h2>
</h1>
</center>
</div>
)
}
}
export default clusterServersDropdown;
In this case, I am able to get output as below:-
Now I am able to print 1st level selected value and all other values of the other dropdown. Now let's say if I select test1 from the second dropdown, how can I fetch this selected value.
A few things need to be fixed;
selectserver
. this.state = {
...
selectserver: "",
...
};
routeChange
handler function should update selectserver
. routeChange = (e) => {
this.setState({ selectserver: e.target.value });
};
this.state.selectserver
as the value.<select
value={this.state.selectserver}
onChange={this.routeChange}
>
...
...
</select>