62

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

3 Answers 3

90

First of all, you can't pass to alert second argument, use concatenation instead

alert("Input is " + inputValue);

Example

However in order to get values from input better to use states like this

var MyComponent = React.createClass({
  getInitialState: function () {
    return { input: '' };
  },

  handleChange: function(e) {
    this.setState({ input: e.target.value });
  },

  handleClick: function() {
    console.log(this.state.input);
  },

  render: function() {
    return (
      <div>
        <input type="text" onChange={ this.handleChange } />
        <input
          type="button"
          value="Alert the text input"
          onClick={this.handleClick}
        />
      </div>
    );
  }
});

ReactDOM.render(
  <MyComponent />,
  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"></div>

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

3 Comments

Why should I update state for every change in input box? Shouldn't reading the value in input box on button click be easier?
What if my input is in separate component from my button?
@PrabhatDoongarwal I'm a total React noob, but I just came across this recommendation in the official react docs to use "controlled components" over "uncontrolled components"
10

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); },

1 Comment

what is the best option in this case?
1

It is Simple:

import {useState} from 'react';
 const[value, setValue] = useState(""); 
    function handle() {
        alert(value)
    }

<input value={value} onChange={(e) => {setValue(e.target.value)}} />
<button onClick={handle}>Button</button>

1 Comment

This does work, but I want to leave a note because this can create additional renders that may not be expected. Using the useState hook, every time the state is changed the component is rendered again. If you have a lot of child elements, this side-effect may be more noticeable. See react.dev/reference/react/useState#returns

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.