What is React 16's React.Fragment?

Brett Cole
2 min readApr 30, 2018

--

React 16 brought with it a lot of new features. A little bit of a new spin on context, being able to return and render an array and being able to display multiple children without adding nodes to the DOM. That last feature is what this blog post will be about.

I like the way that React describes Fragments —

A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

<React.Fragment> is similar to rendering an array. But the difference inside an array is you need to use a comma between each item. With Fragment it’s a great way to display as many component as you want without adding that extra parent div. So your not unnecessarily adding nodes to the DOM tree.

Let me give you an example. React uses an example of table tag and it’s data.

const Example = () => {
return (
<React.Fragment>
<td>Hello</td>
<td>World</td>
</React.Fragment>
)
}

This component will render Hello World. But now here’s the same example with table tag.

const Example = () => {
return (
<table>
<tr>
<td>Hello</td>
<td>World</td>
</tr>
</table>
)
}

Ok so your thinking, “so what they output the same thing”. But if you look in developer tools at the DOM tree we can see the difference.

So to explain a little bit first. That outside div, if your wondering, I included so that I could show you both examples without throwing an error. As we can see with the first two td tags we can include the data from the table without the extra table and tr nodes. So Fragments work great to show data from a table without having to include all the extra structure like in the second part of the example. Fragments also works great displaying li tags or a number of different imported components.

Depending on your build tool setup you can also include the short syntax version, which looks like this.

const Example = () => {
return (
<>
<li>Some info</li>
<li>Some more info</li>
</>
)
}

Personally, I like the longer version just so it’s a quick reference for me and I can’t forget what that’s called. But that’s just me. But if you prefer the short syntax it’s becoming more and more supported.

I really like the new features added with React 16. Between rendering arrays, and Fragments it really begins to open options up to developers.

So that’s it for this blog post. Until next time we meet. I’m outta here.

--

--

Brett Cole
Brett Cole

Written by Brett Cole

Full Stack Developer. Husband. Father.

No responses yet