Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it best practice to surround JSX assigned to variables with parenthesis?

In the example below the output is the same for both x and y. I've seen React code written both ways. Is there a difference? As many of the React code examples I see utilize the parenthesis syntax, I assume there is a reason. If it's best practice, then why is it best practice to surround JSX assigned to variables with parenthesis? If there is another reason what is it?

let x =  <div> Hello World! </div>;
let y = (<div> Hello World! </div>);

console.log(x,y);
like image 673
Bruce Seymour Avatar asked Jul 19 '18 16:07

Bruce Seymour


People also ask

Does JSX need to be in parentheses?

Multiline JSX ExpressionA JSX expression that spans multiple lines must be wrapped in parentheses: ( and ) . In the example code, we see the opening parentheses on the same line as the constant declaration, before the JSX expression begins.

Why do we use {} In React?

Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.

What does parentheses do in JavaScript?

() (parentheses) They are used to contain a list of parameters passed to functions and control structures and they are used to group expressions to control the order of execution. Some functions have no parameters and in this case, the space between parentheses is blank.

Can JSX be assigned to a variable?

Therefore, JSX is designed as a statically-typed language. All the values and variables have a static type and you can only assign a correctly-typed value to a variable.


1 Answers

In general parentheses are used to wrap the JSX code for code clarity...That is,

let y = <ul>
    <li>
        Hello World!
    </li>
</ul>;

is ugly but correct

let y = 
    <ul>
        <li>
            Hello World
        </li>
    </ul>;

is better formatted but syntactically incorrect (will give error on compilation).

So the solution is to use

let y = (
    <ul>
        <li>
            Hello World
        </li>
    </ul>
);

which is the best of both worlds.

UPDATE : The reason for the second code being incorrect is Automatic Semicolon insertion. Thanks to @EricKing for pointing that out.

like image 134
ManavM Avatar answered Oct 30 '22 08:10

ManavM