2

I tried using onChange, onClick, and ref and none of those would work to give me the value of the option I selected

<select ref={input => { this.handleInput(input.value) } }>
    <option value="1">Blah</option>
    <option value="2">Blah2</option>
    <option value="3">Blah3</option>
</select>

As you can see, input.value is showing me undefined. I don't know however else to get the option value, even changing ref to onChange and onClick didn't work

2
  • 3
    Why not use onChange and use the first argument e, then access e.target.value? Commented Dec 9, 2017 at 23:51
  • @Li357 That worked, thank you! I didn't know you can do that Commented Dec 9, 2017 at 23:52

1 Answer 1

2

Try onChange like this:

class App extends React.Component {

  constructor(props){
    super(props)
    this.state = {
      result: ''
    };
  }
  
  handleSelectChange = (event) => {
    this.setState({
      result: event.target.value
    })
  }

  render() {
    return (
      <div>
      <select onClick={this.handleSelectChange}>
          <option value="1">Blah</option>
          <option value="2">Blah2</option>
          <option value="3">Blah3</option>
      </select>
      {this.state.result}
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

I change onClick to onChange. But I got nothing for the first select?. The 2nd and so on is ok
@SulungNugroho I think you have to add [name] attr to your selects tags to define them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.