React - Select element

About

Controlled Component

The react forms components select accept a value attribute that is used to implement a controlled component.

React, instead of using this HTML 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.

form implementing a controlled component written as a class component

class SelectForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: 'green'};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('Your favorite color is: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Pick your favorite color:
          <select value={this.state.value} onChange={this.handleChange}>
            <option value="green">Green</option>
            <option value="red">Red</option>
            <option value="blue">Blue</option>
            <option value="yellow">Yellow</option>
          </select>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(
  <SelectForm />,
  document.getElementById('root')
);
<div id="root"></div>

Powered by ComboStrap