Categories
React Answers

How to select selected option with React JSX?

Spread the love

To select an option in a dropdown menu (select element) using React JSX, we can utilize the value attribute on the <select> element. Here’s an example:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedOption: 'option2' // Assuming 'option2' is the value we want to select initially
    };
  }

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

  render() {
    return (
      <div>
        <select value={this.state.selectedOption} onChange={this.handleChange}>
          <option value="option1">Option 1</option>
          <option value="option2">Option 2</option>
          <option value="option3">Option 3</option>
        </select>
      </div>
    );
  }
}

export default MyComponent;

In this example we have a state variable selectedOption, which holds the value of the currently selected option.

The <select> element has a value attribute set to this.state.selectedOption. This ensures that the option with the matching value will be selected in the dropdown.

  • The onChange event handler (handleChange) updates the state selectedOption whenever the user selects a different option from the dropdown menu.

By managing the state in this way, React will automatically update the selected option in the dropdown based on the selectedOption state variable, providing a controlled component behavior.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *