React dealing with controlled component input forms

In most case react form will works normally until you wanted to set a value in the input and change while changes / start to input in something,

<input type="text" value="some value here" />

and you realised the value does not change no matter how hard you pressed, this is because of the controlled component:

“In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().”

To solve this you will need to change the value state while typing using onChange method:

to solve this you will need to change the value state while typing using onChange method:

 

inputTextChange(e){
  this.setState({
    myInputState: e.target.value
  });
}
...
...
<input type="text" value="{this.state.myInputState}" />

 

lets say you have multiple input and want to change the value for each, you can do like this:

 

<input name="inputName" type="text" value="{this.state.myInputState}" />
...
...

inputTextChange(e){
  let _stateName = e.target.name, val = e.target.value;
  let _thisItem = this.state.myInputsState;
  _thisItem[_stateName] = val;
  _thisItem = _thisItem;

  this.setState({
    myInputsState: _thisItem
  });
}