My State is as follows:
this.state = {
Form: {},
Result: {
Duplicate: false,
ServerError: false
}
};
I want to dynamically add to the Form object with field values as they're entered, so I try the standard way to add dynamic keys:
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
Form[name]: value
});
}
But this produces this syntax error:
66 | const name = target.name;
67 | this.setState({
> 68 | Form[name]: value
| ^
69 | });
70 | console.log(this.state)
71 | }
Is there another way to achieve this?
I believe this is the correct way to achieve it
this.setState(prevState => ({
Form: {
...prevState.Form,
[name]: value,
}
}));
You've just used invalid syntax to create a dynamic object key. You need do this:
this.setState({
Form: {
...this.state.Form,
[name]: value
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With