<input
defaultValue={this.props.str.name}
ref={(input) => { this.state.name = input; }}
name="name"
type="text"
className="form-control"
onChange={this.handleInputChange}
/>
handleInputChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
if(this.state.name.value === "") {
this.msg.show('Required fields can not be empty', {
time: 2000,
type: 'info',
icon: <img src="img/avatars/info.png" role="presentation"/>
});
}
I'm trying to set the default value like that and wanted to access it as well. I did like this and accessed the value with this.state.name.value
but the thing is its working but showing the warning as
Do not mutate state directly, Use setState() react/no-direct-mutation-state .
Because, you are mutating the state value inside ref callback method to store the node ref, Here:
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:
Since you are using controlled input element, ref is not required. Directly use
this.state.name
with input element value property andthis.state.name
to access the value.Use this:
If you wanted to use
ref
then store the ref directly on instance, remove value property and you can remove theonChange
event also, Use it like this:Now use this
ref
to access the value like this:this.el.value
you can instead clone the entire property value inside the with spread operator and then reform or edit the value for example :