In React 16.2, improved support for Fragments
has been added. More information can be found on React\'s blog post here.
We are all familiar with the fol
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.
<React.Fragment>...</React.Fragment>
, we can add a parent tag to our JSX elements without adding an extra node to the DOM.<>...</>.
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>
I prefer to use the shorthand version of React.Fragment
<>
<p>....</p>
<div>....</div>
</>
is same as
<React.Fragment>
<p>....</p>
<div>....</div>
</React.Fragment>
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.
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