How do I write a single setState method to update the value for multiple input elements when the state object is nested as shown below?
Note: State shouldn't be mutated
When the state is not nested, we could do it like:
this.setState({ [event.target.name]: event.target.value });
But how do we do it when the state object is nested?
class FormContainer extends Component {
constructor () {
this.state = {
formControls: {
email: {
value: ''
},
user: {
value: ''
},
password: {
value: ''
}
}
}
}
changeHandler = event => {
const name = event.target.name;
const value = event.target.value;
this.setState({
//code here
});
}
render() {
return (
<form>
<input type="email"
name="email"
value={this.state.formControls.email.value}
onChange={this.changeHandler}
/>
<input type="text"
name="user"
value={this.state.formControls.name.value}
onChange={this.changeHandler}
/>
<input type="password"
name="password"
value={this.state.formControls.password.value}
onChange={this.changeHandler}
/>
</form>
);
}
}