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);
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.
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.
() (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.
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.
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.
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