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 :
When this code is compiled it turns into the following :
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 :
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 :
Conclusion
Now you know why when you want to use multiple tags when using JSX, those tags must be in a wrapper.
Top comments (0)