React JSX: selecting "selected" on selected <select> option
Asked 07 September, 2021
Viewed 1.3K times
  • 59
Votes

In a React component for a <select> menu, I need to set the selected attribute on the option that reflects the application state.

In render(), the optionState is passed from the state owner to the SortMenu component. The option values are passed in as props from JSON.

render: function() {
  var options = [],
      optionState = this.props.optionState;

  this.props.options.forEach(function(option) {
    var selected = (optionState === option.value) ? ' selected' : '';

    options.push(
      <option value={option.value}{selected}>{option.label}</option>
    );
  });

// pass {options} to the select menu jsx

However that triggers a syntax error on JSX compilation.

Doing this gets rid of the syntax error but obviously doesn't solve the problem:

var selected = (optionState === option.value) ? 'selected' : 'false';

<option value={option.value} selected={selected}>{option.label}</option>

I also tried this:

var selected = (optionState === option.value) ? true : false;

<option value={option.value} {selected ? 'selected' : ''}>{option.label}</option>

Is there a recommended way of solving this?

14 Answer