Why are Fragments in React 16 better than container divs?
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’s a tiny bit faster and has less memory usage (no need to create an extra DOM node). This only has a real benefit on very large and/or deep trees, but application performance often suffers from death by a thousand cuts. This is one cut less.
- Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationship, and adding
div
s in the middle makes it hard to keep the desired layout while extracting logical components. - The DOM inspector is less cluttered. :-)
You can find the descriptions of some other use cases in this React issue: Add fragment API to allow returning multiple components from render
- Added features not possible before with JSX
- Better semantic jsx markup. Wrapper elements are used when needed not because they are forced to.
- Less overall dom markup (increased render performance and less memory overhead)
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>