Bruce Seymour
Bruce Seymour

Reputation: 1598

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

Upvotes: 17

Views: 4344

Answers (3)

mdsadiq
mdsadiq

Reputation: 890

It is advised that way for two reasons,

One, It helps javascript interpreter to find the end of assignment, as sometimes, the interpreter might read statement like return , which is present in the middle of the code and end the assignment right there.

Second, It helps with readability & indentation, whoever reads the code understands where assignment ends.It is very easy to lose track when you are reading through a big file.

return 
  <div> Your text here </div>

will be interpreted as

return;
<div> Your text here </div>;

So, to avoid this, prefer parentheses around JSX

return (
    <div> 
       Your text here 
    </div>
)

Upvotes: 8

ManavM
ManavM

Reputation: 3098

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.

Upvotes: 20

Ashley Fernandes
Ashley Fernandes

Reputation: 1207

While assigning HTML code to a variable (jsx), parenthesis won't make much difference, but I would like to point out its advantage while using arrow functions or even while making a stateless component.

const FunctionName = () => {
 return <p>Hello World </p>;
};

notice in the above code we have to write the return keyword while using the curly braces, but if you want to be more concise you can use parenthesis...

const FunctionName = () => (
 <p> Hello World </p>
); 

//or write it in one line as well

const FunctionName = () => ( <p> Hello World </p> );  

Upvotes: 1

Related Questions