React 16 - Returning multiple children from a component using Fragments

In this post, we're going to take a look at another huge improvement that was introduced in React 16 called Fragments.

What Fragments enables us to do is to return multiple children from a component.

This is a big deal because in the pre-react 16 era you could only return one child element — meaning if you had multiple children you had to wrap them in a div or something similar.

Luckily with the introduction of Fragments this is not the case anymore.

To see how this works, consider the following scenario.

We got two react components — Title and Content — that we want to return as children in the rendering of a third component called Article.

First attempt to introduce Fragments

In the first release of React 16, Fragments were done by returning an array of the children.

So to be able to return Title and Content as children of Article, we only have to put them in an array in the render function.

const Title = ({title}) => (  
  <h1>{title}</h1>
);

const Content = ({content}) => (  
  <p>{content}</p>
);

const Article = ({article}) => [  
    <Title title={article.title}/>,
    <Content content={article.content}/>
  ];

Cool right? Well it gets better.

React 16.2 — a new variant of Fragments

With the release of React 16.2 a new variant of Fragments was introduced — the higher order component — <Fragment>.

This kind of higher order component makes more sense syntactically since it's more aligned with the JSX syntax.

All you now have to do is to wrap all the children you want to return from a component with the Fragment tag.

const Fragment = React.Fragment;

const Title = ({title}) => (  
  <h1>{title}</h1>
);

const Content = ({content}) => (  
  <p>{content}</p>
);

const Article = ({article}) => (  
  <Fragment>
    <Title title={article.title}/>
    <Content content={article.content}/>
  </Fragment>
);

If we now render this component we'll see that the final html won't contain any wrapping tags.

<h1>Hello World</h1>  
<p>Lorem Ipsum</p>  

A Shorthand for the Fragments component

Now, since this is probably something that will be widely used, they've made the smart move of introducing a shorthand.

Instead of using the <Fragment> tag, we can use an empty tag — <> — to create a Fragment.

const Title = ({title}) => (  
  <h1>{title}</h1>
);

const Content = ({content}) => (  
  <p>{content}</p>
);

const Article = ({article}) => (  
  <>
    <Title title={article.title}/>
    <Content content={article.content}/>
  </>
);

Now it's worth mentioning that if you want the key attribute or anything like that you can not use the shorthand. In those cases you need to use the full <Fragment> tag.

Demo

To see a running example of the code used in this post, checkout this CodePen