Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) });   } }); 
like image 897
Lucas Avatar asked Jul 17 '16 10:07

Lucas


People also ask

How do I get the value of a text box in React?

To get the value of an input field in React:Use event. target. value to get the input field's value and update the state variable.

How do I get input data in React?

To get input values on form submit in React:Store the values of the input fields in state variables. Set the onSubmit prop on the form element. Access the values of the input fields in your handleSubmit function.

How get value from select in React?

Controlled Components to Get Dropdown Menu Value in React First, we must set up an event listener on the <select> element and define an event handler. In our example, it takes one argument - e (short for event) and calls the setFruit() function. To set the state with the selected value, we access the e. target.


2 Answers

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

like image 188
Dmitriy Nevzorov Avatar answered Sep 17 '22 15:09

Dmitriy Nevzorov


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

like image 41
Piyush.kapoor Avatar answered Sep 19 '22 15:09

Piyush.kapoor