[reactjs] How to get input text value on click in ReactJS

I am learning ReactJS and I want to understand how to get the input text values in ReactJS using simple onclick event. I have followed there tutorial and although i am able to get the parameter of text input. But somehow i am not able to get its value. I know this is a dumb question, but i am struggling with this. Please check my code and let me know what's wrong with it.

var MyComponent = React.createClass({
  handleClick: function() {
    if (this.refs.myInput !== null) {
        var input = this.refs.myInput;
            var inputValue = input.value;
      alert("Input is", inputValue);
    }
  },
  render: function() {
    return (
      <div>
        <input type="text" ref="myInput" />
        <input
          type="button"
          value="Alert the text input"
          onClick={this.handleClick}
        />
      </div>
    );
  }
});

ReactDOM.render(
  <MyComponent />,
  document.getElementById('container')
);

Here is jsfiddle for the same : jsfiddle link

This question is related to reactjs

The answer is


There are two ways to go about doing this.

  1. Create a state in the constructor that contains the text input. Attach an onChange event to the input box that updates state each time. Then onClick you could just alert the state object.

  2. handleClick: function() { alert(this.refs.myInput.value); },