As you may know, the JSX is a mere syntactic sugar. It is not part of the Ecmascript specification. So, when compiled, JSX becomes something like this:
React.createElement(component, props, ...children);
Therefore, we now understand the need to only return one React element per component. This is valid, since it returns only one element:
function MyComponent() {
return (
<React.Fragment>
<strong>Foo</strong>
<span>Bar</span>
</React.Fragment>
);
}
However, this other example is no longer valid, since a component cannot return more than two elements:
function MyComponent() {
// ❗️ Errado!
return (
<strong>Foo</strong>
<span>Bar</span>
);
}
That way, if you need to return more than two elements on the same level, React forces you to involve them in a single component. Prior to the introduction of the fragments, you should use an HTML tag or some other generic component, which was not always ideal, since you would be inserted another HTML element in the DOM, may even affect accessibility or hinder componentization so important to React.
To documentation on fragments explains these motivations with a little more depth.
What are the advantages of using the <React.Fragment>
in comparison to a <div>
?
As stated above, the main advantage of using a fragment is that you can return multiple elements to the same level without necessarily having to involve them in some component that will render some node in the DOM.
For example, in the section below, a <div>
will be rendered:
function MyComponent() {
return (
<div>
<strong>Foo</strong>
<span>Bar</span>
</div>
);
}
ReactDOM.render(<MyComponent />, document.body);
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
But in this other example, no other tag besides strong
and span
will be inserted in the FOD, since a fragment has been used:
function MyComponent() {
return (
<React.Fragment>
<strong>Foo</strong>
<span>Bar</span>
</React.Fragment>
);
}
ReactDOM.render(<MyComponent />, document.body);
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
In which cases it is appropriate to use the <div>
and in which cases should I use the Fragment
?
Use the div
— or any other component that will render something in the DOM tree - when you want it to happen. If you do not want the "wrapping" component to be rendered in the DOM, use a fragment.
You can also use
<>
and</>
in place of tag<React.Fragment>
. The effect is the same, but it is easier to see the code and realize that that element will not be rendered.– Rafael Tavares