Home >Web Front-end >JS Tutorial >Why Do Multiple JSX Tags Need To Be Wrapped? : Wrapping Into Another Tag or Fragment

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

Susan Sarandon
Susan SarandonOriginal
2024-12-03 01:22:11662browse

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 :

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

When this code is compiled it turns into the following :

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

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 :

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

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 :

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


Conclusion

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

The above is the detailed content of Why Do Multiple JSX Tags Need To Be Wrapped? : Wrapping Into Another Tag or Fragment. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn