DEV Community

Cover image for Why Do Multiple JSX Tags Need To Be Wrapped? : Wrapping Into Another Tag or Fragment
Sonay Kara
Sonay Kara

Posted on

Why Do Multiple JSX Tags Need To Be Wrapped? : Wrapping Into Another Tag or Fragment

Why do multiple JSX tags need to be wrapped?

JSX is a syntax extension for JavaScript. You can write HTML formatting inside a JavaScript file.

When using JSX, you know that when you want to use more than one tag, these tags must be in a wrapper. In this article, I will explain the reasons for this necessity.


JSX is written in JavaScript code and compiled "to JavaScript" by tools like Babel to make it understandable by the browser.

Now let's write an example JSX for React.js :

Image description

When this code is compiled it turns into the following :

Image description

When this code is compiled, you can understand that the React.createElement function should return only one root element by examining the compiled code.


Now you know why when you want to use multiple tags when using JSX, those tags must be in a wrapper. So what do we use for the wrapper?
Let's explain.

1. Wrapping with HTML Tag

You can use the div tag or use any other tag. But div tags are generally used.

Example :

Image description

2. Fragment Usage

This empty tag is called a Fragment ( <></> ). Fragments let you group things without leaving any trace in the browser HTML tree.

Example :

Image description


Conclusion

Now you know why when you want to use multiple tags when using JSX, those tags must be in a wrapper.

Top comments (2)

Collapse
 
wizard798 profile image
Wizard

Just thanks for this, I always wanted to know why we had to do this wrapping, cause most in all courses, they just show this in first basic lectures then never go there, so something always left behind on how react works which are actually simple but never known cause of less knowledge of React basics, thanks for this, this helped me that why basics are needed
Keep going

Collapse
 
sonaykara profile image
Sonay Kara • Edited

you are welcome. Sharing information is very important. I will continue.