think123 think123 - 4 months ago 64
HTML Question

How to get value of textbox in React?

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

Answer

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

Comments