Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "(.....);" and "{......}" in react?

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
    }});
}

1

like image 588
Alternating pulse Avatar asked Dec 16 '18 16:12

Alternating pulse


1 Answers

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};
    });
}
like image 158
T.J. Crowder Avatar answered Dec 19 '22 16:12

T.J. Crowder