mouchin777
mouchin777

Reputation: 1588

React, set an 'option selected' based on a state value

I have this state

this.state = {
        emotionRating: this.props.emotionRating
    };

And this selector

<select className="emotion-selector" value={this.state.value}  onChange={this.props.handleChange}>
                            <option value="5" >Very Good (5)</option>
                            <option value="4" >Good (4)</option>
                            <option value="3" >Neutral (3)</option>
                            <option value="2" >Bad (2)</option>
                            <option value="1" >Awful (1)</option>
                        </select>

I want to set a selected attribute to the option value based on the state of emotionRange, something like this

<select className="emotion-selector" value={this.state.value}  onChange={this.props.handleChange}>
                            <option value="5" {...this.state.emotionRating == 5 ? "selected" : null}>Very Good (5)</option>
                            <option value="4" {...this.state.emotionRating == 4 ? "selected" : null}>Good (4)</option>
                            <option value="3" {...this.state.emotionRating == 3 ? "selected" : null}>Neutral (3)</option>
                            <option value="2" {...this.state.emotionRating == 2 ? "selected" : null}>Bad (2)</option>
                            <option value="1" {...this.state.emotionRating == 1 ? "selected" : null}>Awful (1)</option>
</select>

But that wont work

Upvotes: 1

Views: 955

Answers (1)

Sohail Ashraf
Sohail Ashraf

Reputation: 10604

Remove the selected attribute from options and let the React to select the option based on value.

React, instead of using this selected attribute, uses a value attribute on the root select tag. This is more convenient in a controlled component because you only need to update it in one place

 <select
      className="emotion-selector"
      value={this.props.emotionRating}
      onChange={this.props.handleChange}
    >
      <option value="5">Very Good (5)</option>
      <option value="4">Good (4)</option>
      <option value="3">Neutral (3)</option>
      <option value="2">Bad (2)</option>
      <option value="1">Awful (1)</option>
    </select>

Live Example

https://codepen.io/gaearon/pen/JbbEzX?editors=0010

Upvotes: 1

Related Questions