Why do we need parentheses around multi-line JSX expressions?

Question

Why do we need parentheses around multi-line JSX expressions?

Answer

We want to use parentheses around multi-line JSX expressions to make sure we are avoiding JavaScript’s automatic semicolon insertion which will add semicolons (based on rules given by the JavaScript specifications) to terminate statements when we don’t necessarily want/expect that behavior in a JSX expression.

14 Likes

Hi,
Please can you post an example for above explanation.

2 Likes

Hello!

I believe aubsrey is talking about something like this:

Wrong usage

let myVariable = <div><h1>&nbsp; Hello world!</h1></div>;

Semicolon “;” inside “&nbsp;” breaks nesting, as it is not treated as part of JSX expression, but it is treated as basic js syntax.


Correct usage

let myVariable = ( <div><h1>&nbsp; Hello world!</h1></div> );

this way any semicolon between “(” and “)” is ignored by js interpreter.


17 Likes

Hi,

I think aubsrey mean, that javascript reads every line and ends it with a semicolon.
Like this:

let myVariable = 
<div> ; 
  <h1>hello world</h1> ;
</div> 

That’s way you need the parentheses:

 let myVariable = (
 <div>
    <h1>hello world</h1>
 </div>
)

:smiley:

28 Likes

Does this mean that if I don’t add semicolons at the end of each of my JSX expressions, JS will automatically insert them for me at each line break?

Perhaps, it means that JavaScript automatically inserts semicolon when we don’t insert it.

Hence, we use parenthesis in multiline JSX, so that JavaScript doesn’t insert it for us, thinking that our multiline JSX is just a JavaScript statement whose author simply forgot to add semicolons at the end of the individual lines. @mtf Kindly tell if this is correct

I don’t believe it has anything to do with semi-colons. It’s the syntax that tells the compiler to treat it as a single JSX element which will be compiled into a React object. The only semi-colon in that statement would go at the very end, after the closing ).

9 Likes

Considering this answer in stackoverflow it seems it has something to do with automatic semi-colon insertion. This article in MDN is also referred in the answer.

4 Likes

The rendering still works fine without parentheses to me so I assume it’s for readability?

1 Like

The basic reason for adding parentheses around our multi-line JSX is to eliminate anomalies that Javascript might perform such as the insertion of semicolons when we do not need it but it also gives our code structure and readability which is a very important thing in programming as it easies debugging

1 Like

According to what I’ve learned now, if we want to have a well-organized code with JSX it’s more feasible to use parentheses and group our JSX elements inside a variable

const myContainer = (
<div>
<h2>Hello World</h2>
</div>
)

thank you so much!!!

yes l agree to make semicolons and also we use to make understandable code structure