{ this.state.name = input; }}
name=\"name\"
type=\"text\"
className=\"form-control\"
on
you can instead clone the entire property value inside the with spread operator and then reform or edit the value for example :
state = {Counters: [{id:1,value:1},{id: 2,value: 2},{id: 3,value: 3},{id: 4,value: 4}]}
increment = (Counter) => {
//This is where the state property value is cloned
const Counters = [...this.state.Counters];
console.log(Counters);
const index = Counters.indexOf(Counter)
Counters[index].value++
this.setState({
Counters: this.state.Counters
})
}
Getting "Do not mutate state directly, Use setState()", Why?
Because, you are mutating the state value inside ref callback method to store the node ref, Here:
this.state.name = input;
Solution:
Don't use state variable to store the reference, You can directly store them in component instance because that will not change with time.
As per DOC:
The state contains data specific to this component that may change over time. The state is user-defined, and it should be a plain JavaScript object.
If you don’t use it in render(), it shouldn’t be in the state. For example, you can put timer IDs directly on the instance.
Since you are using controlled input element, ref is not required. Directly use this.state.name
with input element value property and this.state.name
to access the value.
Use this:
<input
value={this.state.name || ''}
name="name"
type="text"
className="form-control"
onChange={this.handleInputChange}
/>
If you wanted to use ref
then store the ref directly on instance, remove value property and you can remove the onChange
event also, Use it like this:
<input
ref={el => this.el = el}
defaultValue={this.props.str.name}
name="name"
type="text"
className="form-control"
/>
Now use this ref
to access the value like this:
this.el.value