I have an issue with react when I want to change the selected option. The problem is that the value is an object and I can\'t pass it in option value attribut.
See t
I assume you want only one option will be selected. So the easiest way would be to set selectedIndex. When using construct always think of value type. this.state = { selectedIndex: 0}
Now you've state with selectedIndex object which firstly is equal to 0.
In render method you could then just check for the index:
{this.props.listOption.map((option, index) => {
this.state.selectedIndex == index ? (
<option key={index} value={option.obj} selected>option.name</option>
): (
<option key={index} value={option.obj}>option.name</option>
))}
And on handle change setState with e.target.key.
I may have left syntax errors... Altought I hope it helps.
You can make use of index
of options
class Selector extends React.Component {
contructor(props) {
super(props);
this.state = { obj: null }
this.handleChange = this.handleChange.bind(this)
}
handleChange(e) {
this.setState({obj: this.props.listOption[e.target.value].obj})
}
render() {
<select onChange={handleChange}>
{this.props.listOption.map((option, index) =>
<option key={index} value={index}>
{option.name}
</option>
)}
</select>
}
}
Moreover, I set obj in state as null in the constructor Is there a right way to do it?
I depends on your requirement. If you want to show at least one option as selected you can keep that instead of null
Convert the object to JSON string, and pass it as value.
And convert the string back to object in the handler.
handleChange(event) {
let obj = JSON.parse(event.target.value); //object
}
render() {
<select onChange={handleChange}>
{this.props.listOption.map((option, index) =>
<option key={index}
value={JSON.stringify(option)}> //pass object string as value
{option.name}
</option>
)}
</select>
}
Try this following code,
import React from 'react';
class LocationDemo extends React.Component {
constructor(props) {
super(props);
this.state = {
searchLoc: undefined,
selectedLoc: "",
locs:[
{"name" : "Kerala","districts":["Ernakulam", "Trivandrum"]},
{"name" :"Tamil Nadu","districts" :["Palani","Tiruchi"]}
],
};
this.handleChangeLocation = this.handleChangeLocation.bind(this);
}
handleChangeLocation = (event) => {
this.setState({ selectedLoc: event, searchLoc: event.target.value }
, () => console.log("searchLoc", this.state.searchLoc));
}
render() {
return (
<select class="cls-location" id="id-location"
onChange={this.handleChangeLocation}
value={this.state.locs.find(obj => obj.value === this.state.selectedLoc)}
required
>
{
this.state.locs.map(loc => {
return (
<option name={loc.name} value={JSON.stringify(loc)}>{loc.name}</option>
)
})
}
</select>
);
}
}
export default LocationDemo;