I am getting error shown in image for the below code:
handlechange(event) {
this.setState (prevState => {
return(
checked : !prevState.checked
);});
}
But when I changes round brackets after "return" into curly, it runs fine. I mean what's happening under the hood? What causes the error to go away?
handlechange(event) {
this.setState (prevState => {
return{
checked : !prevState.checked
}});
}
This isn't a React thing. Your first example is just invalid JavaScript syntax.¹ Your second example is valid syntax, returning an object created via an object initializer (often called an object "literal," {checked: !prevState.checked}
).
¹ The ()
after return
wrap an expression, and then within the expression you have checked: !prevState.checked
which looks like a labelled statement. But you can't put a labelled statement where an expression is expected.
Side note: Another way to write that is to use property destructuring in the parameter list and a shorthand property in the object initializer:
handlechange(event) {
this.setState(({checked}) => {
checked = !checked;
return {checked};
});
}
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