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 the following code:
class Selector extends React.Component { contructor(props) { super(props) this.state = { obj: null } this.handleChange = this.handleChange.bind(this) } handleChange(e) { this.setState({obj: e.target.value}) } render() { <select onChange={handleChange}> {this.props.listOption.map((option, index) => <option key={index} value={option.obj}> {option.name} </option> )} </select> } }
and with
<Selector option={[{name: "name", obj:{...}}, ...]}>
I need to change the state of the component with the value of the selected option. What I get when the state change is "object Object"
. I suppose this happens because react can't embed javascript object in attribut of final view. I am right?
Moreover, I set obj
in state as null in the constructor Is there a right way to do it?
To add select option with object as the value attribute value with React, we can set the value attribute to the index and then select the object from the index from the options array. We have an array of options that we render as options in the select drop down. To do the rendering, we call options.
Getting the Selected Value To fetch the selected value from the select element, you can use the onChange event handler prop. Just like the input or textarea elements, you can use the onChange event handler to get the value from the event object.
Objects cannot be used as keys. React js requires a key to be a string or a number and should be unique.
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> }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With