React Fragments allow you to wrap or group multiple elements without adding an extra node to the DOM. This can be useful when rendering multiple child elements/components in a single parent component.
Why do we use fragments in React? React fragments serve as a cleaner alternative to using unnecessary divs in our code. These fragments do not produce any extra elements in the DOM, which means that a fragment's child components will render without any wrapping DOM node.
The main difference between React. Fragment vs div is that using a React. Fragment will not add any additional elements into the DOM tree, whereas, using a div will add a div to the DOM tree.
<> is the shorthand tag for React. Fragment which allows us to group a list of elements without wrapping them in a new node. The only difference between them is that the shorthand version does not support the key attribute.
div
s in the middle makes it hard to keep the desired layout while extracting logical components.You can find the descriptions of some other use cases in this React issue: Add fragment API to allow returning multiple components from render
Adding to all answers above there is one more advantage: code readability, Fragment
component supports a syntactic sugar form, <>
. Thus the code in your question can be written more easily as:
render() {
return (
<>
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</>
);
}
According to docs,
In React, this desugars to a
<React.Fragment/>
element, as in the example from the previous section. (Non-React frameworks that use JSX may compile to something different.)
Clutter-free, right ?
Note that you still need to use <Fragment>
syntax if you need to provide key
to the fragment.
It as simple as when you don't need a wrapper element you aren't forced to use one. Having less elements is great but I think the biggest benefit is being able to render elements in jsx that weren't previously possible and adding better semantic meaning to wrapper elements because they are optional now.
This wasn't possible before:
<select>
{this.renderOptions()}
</select>
Glancing at the following in React 15 you can't tell if the wrapper element is needed or not:
<span>
<h1>Hello</h1>
{this.getContent()}
</span>
As per the reactjs.org docs most important needs of <Fragment> </Fragment>
instead of div's are to avoid breaking HTML semantics. When we use div's instead of <Fragment> </Fragment>
we break the HTML semantics.
To know more about html semantics. please click and also there are cases where if you use div's instead of Fragments it will be invalid html, for example look at this code:
class Columns extends React.Component {
render() {
return (
<div>
<td>Hello</td>
<td>World</td>
</div>
);
}
}
<table>
<tr>
<div>
<td>Hello</td>
<td>World</td>
</div>
</tr>
</table>
Fragments solve this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With