React selecting option with object as attribute value
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>
}