ChatGPT解决这个技术问题 Extra ChatGPT

React JSX: selecting "selected" on selected <select> option

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?


H
HoldOffHunger

React makes this even easier for you. Instead of defining selected on each option, you can (and should) simply write value={optionsState} on the select tag itself:

<select value={optionsState}>
  <option value="A">Apple</option>
  <option value="B">Banana</option>
  <option value="C">Cranberry</option>
</select>

For more info, see the React select tag doc.

Also, React automatically understands booleans for this purpose, so you can simply write (note: not recommended)

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

and it will output 'selected' appropriately.


With the current version of React (0.9) setting the selected attribute on options does not work at all. Set the value attribute on the select element instead.
i load data with ajax.defaultValue is not working for me. value is working but i cant select another item on select list.List is opening but when i select one of them it select value item.Any idea ?
@user1924375 you should use onChange event onChange={this.handleSelect} and set state value for your component, for example: 'handleSelect: function() { this.setState({value: event.target.value});}` This would rerender your select component with new selected item. Hope it would help you.
Rather use defaultValue to initialize
Try to use defaultValue on is rendered, the must already be available or else it won't work. If you async-load the options after rendering the instead of setting selected on