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 following code:
render() {
return (
// Extraneous div element :(
<div>
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</div>
);
}
Yes, we need a container div, but it's not that big of a deal.
In React 16.2, we can do this to avoid the surrounding container div:
render() {
return (
<Fragment>
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</Fragment>
);
}
In either case, we still need need a container element surround the inner elements.
My question is, why is using a Fragment
preferable? Does it help with performance? If so, why? Would love some insight.
div
is that you don't always want a wrapper element. Wrapper elements have a meaning and usually you need additional styles for that meaning to be removed.<Fragment>
is just syntactic sugar that is not rendered. There are situations when creating a wrapper is very difficult, for example in SVG where<div>
cannot be used and<group>
is not always what you want.