Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I change my input value in React even with the onChange listener

I am quite new to React and after going through some tutorials, I was trying the below code of mine.

I made one component, passed props to it from a store, on componentWillMount I make a new state for component. Rendering is fine till now.

Next I bound my state to value of an input box and I have onChange listener as well. Still, I can't change my values in the field.

Since, I am from Angular background, I am assuming binding input's value to state like below will automatically update the property name in state object. Am I wrong here?

componentWillMount(){     this.setState({         updatable : false,         name : this.props.name,         status : this.props.status     }); }  //relevant DOM from component's render function <input className="form-control" type="text" value={this.state.name} id={'todoName' + this.props.id} onChange={this.onTodoChange.bind(this)}/>  onTodoChange(){     console.log(this);     //consoling 'this' here, shows old values only.     //not sure how and even if I need to update state here.     // Do I need to pass new state to this function from DOM     //TODO: send new data to store } 

My onTodoChange function console the value of this which has same value of state as while initializing. How do I go about changing state by typing in input boxes, so that I can send them to the stores?

like image 381
Saurabh Tiwari Avatar asked Jan 19 '17 07:01

Saurabh Tiwari


People also ask

Can't change input value React?

To solve the issue of being unable to type in an input field in React, make sure to use the defaultValue prop instead of value for uncontrolled input fields. Alternatively, set an onChange prop on the field and handle the change event. Here is an example of how the issue occurs.

How do I change my onChange value in React?

To modify the value of a textarea using onChange in React: Add an onChange prop to the textarea setting it to a function. Store the value of the textarea in the state via the useState hook. Update the state variable every time the user types into the textarea.


1 Answers

Unlike in the case of Angular, in React.js you need to update the state manually. You can do something like this:

<input     id={'todoName' + this.props.id}     className="form-control"     type="text"     value={this.state.name}     onChange={e => this.onTodoChange(e.target.value)} /> 

And then in the function:

onTodoChange(value){         this.setState({              name: value         });     } 

Also, you can set the initial state in the constructor of the component:

  constructor (props) {     super(props);     this.state = {         updatable: false,         name: props.name,         status: props.status     };   } 
like image 77
César Landesa Avatar answered Oct 05 '22 19:10

César Landesa