33

I just started using React.js, and I'm just not sure whether there is a special way to get the value of a textbox, returned in a component like this:

var LoginUsername = React.createClass({
  render: function () {
    return (
      <input type="text" autofocus="autofocus" onChange={this.handleChange} />
    )
  },
  handleChange: function (evt) {
    this.setState({ value: evt.target.value.substr(0, 100) });
  }
});

2 Answers 2

39

As described in documentation You need to use controlled input. To make an input - controlled you need to specify two props on it

  1. onChange - function that would set component state to an input value every time input is changed
  2. value - input value from the component state (this.state.value in example)

Example:

  getInitialState: function() {
    return {value: 'Hello!'};
  },
  handleChange: function(event) {
    this.setState({value: event.target.value});
  },
  render: function() {
    return (
      <input
        type="text"
        value={this.state.value}
        onChange={this.handleChange}
      />
    );
  }

More specifically about textarea - here

3
  • So how would I use the above to get the current value of the textbox?
    – Lucas
    Jul 17, 2016 at 11:10
  • By replacing input element on textarea Jul 17, 2016 at 11:21
  • @DmitriyNevzorov how should I achieve the same thing on the functional component.
    – Gopi P
    Mar 29, 2020 at 2:44
7

just update your input to the value

var LoginUsername = React.createClass({
  getInitialState:function(){
     return {
        textVal:''
     }
 },
  render: function () {
    return (
      <input type="text" value={this.state.textVal} autofocus="autofocus" onChange={this.handleChange} />
    )
  },
  handleChange: function (evt) {
    this.setState({ textVal: evt.target.value.substr(0, 100) });
  }
});

Your text input value is always in the state and you can get the same by this.state.textVal

4
  • Could you please provide a use case scenario for the above?
    – Lucas
    Jul 17, 2016 at 11:10
  • If you want to prefill the textinput from the server , then you need to a field in the state Jul 17, 2016 at 11:13
  • I'm trying to access the value from outside LoginUsername - right now I'm trying to use LoginUsername.state.textVal, but it isn't working for me...
    – Lucas
    Jul 17, 2016 at 11:17
  • then u can use ref Jul 17, 2016 at 11:23

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.