React fragments, what they are and how to use them

I came across a new feature introduced in React 16 the other day called fragments. They look pretty useful so I decided to put together an example of how they might be used when building components.

What are they?

Fragments are a syntax that allow you to build a react component with multiple nodes or subcomponents, without requiring a wrapper element.

Until now, if you needed to build a react component that consisted of multiple elements, you would have to wrap them in a div or container of some kind, otherwise you'd get the following syntax error:

Adjacent JSX elements must be wrapped in an enclosing tag

Well now, the error produced looks like this:

Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

Interesting, so this JSX error is suggesting we can use fragments instead of just wrapping everything in our component in a random unsemantic HTML tag, great!

How can I use them?

The syntax for react fragments is dead simple. Instead of wrapping all the elements in a <div></div>, wrap them in a <React.Fragment></React.Fragment>, or the shorthand syntax, <></>.

Here's what that might look like in a component consisting of 2 subcomponents:

render() {
    return <React.Fragment>
        <SubComponentOne />
        <SubComponentTwo />
    </React.Fragment>;
}

When this is rendered on the page, it'll just render the contents of SubComponentOne and SubComponentTwo.

When would I use Fragments?

Of course it is possible to structure a web app in such a way that fragments are unnecessary, but now that we have this tool we don't have to. If the situation calls for it, I see no reason not to use fragments in place of wrappers for cleaner HTML output. An example of this could be when you're trying to maintain good semantic use of HTML in your site or app.

Let's take a look at a simple react app that displays an article using semantic HTML:

HTML

<article id="app"></article>

React

const data = {
  title: "Here is the header",
  intro: "Gravida donec per augue cursus feugiat dis odio, ac mauris nisi malesuada placerat aliquam accumsan tellus, himenaeos ipsum montes volutpat penatibus porttitor.",
  list: {
    intro: "Per augue cursus feugiat:",
    items: [
      { "name": "John", "age": 42 },
      { "name": "Nina", "age": 31 },
      { "name": "Will", "age": 25 },
      { "name": "Alex", "age": 27 },
      { "name": "Amy", "age": 36 },
    ] 
  },
  footer: "Here is a footer",
};

class ArticleHeader extends React.Component {
  render() {
    return <header>
      <h1>{data.title}</h1>
    </header>;
  }
}

class ArticleMain extends React.Component {
  render() {
    return <main>
      <p>{data.intro}</p>
      <PersonList />
    </main>;
  }
}

class PersonList extends React.Component {  
  render() {
    return <React.Fragment>
      <p>{data.list.intro}</p>
      <ul>
        { 
          data.list.items.map((item, i) => {
            return <li key={i}>{item.name}, {item.age}</li>;
          })
        }
      </ul>
    </React.Fragment>;
  }
}

class ArticleFooter extends React.Component {
  render() {
    return <footer>
      <p>{data.footer}</p>
    </footer>;
  }
}

class Article extends React.Component {
  render() {
    return <React.Fragment>
      <ArticleHeader />
      <ArticleMain />
      <ArticleFooter />
    </React.Fragment>
  }
}

ReactDOM.render(<Article />, document.getElementById('app'));

You can see in this code there are two components where we've made use of fragments in order to avoid cluttering the final output, in the Article component, and the PersonList component.

Since the PersonList component returns a short intro paragraph as well as a list, we can use the fragments to avoid having to wrap both of these elements in a div.

The Article component loads directly into an article tag and the ArticleHeader, ArticleMain and ArticleFooter components construct semantic HTML elements, so we want them to be direct children of the article element, without any extra divs inbetween.

This is what the final HTML output looks like:

<article id="app">
    <header>
        <h1>Here is the header</h1>
    </header>
    <main>
        <p>Gravida donec per augue cursus feugiat dis odio, ac mauris nisi malesuada placerat aliquam accumsan tellus, himenaeos ipsum montes volutpat penatibus porttitor.</p>
        <p>Per augue cursus feugiat:</p>
        <ul>
            <li>John, 42</li>
            <li>Nina, 31</li>
            <li>Will, 25</li>
            <li>Alex, 27</li>
            <li>Amy, 36</li>
        </ul>
    </main>
    <footer>
        <p>Here is a footer</p>
    </footer>
</article>

And here's a CodePen of the example:

Summary

React fragments are simple, and useful. Just use <React.Fragment></React.Fragment> or <></> to wrap the elements within your render functions whenever you feel the need for a wrapper div, and keep your output clean!