Tutorial

Returning Multiple Children Using React Fragments

Published on April 14, 2018
Default avatar

By Alligator.io

Returning Multiple Children Using React Fragments

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

With the introduction of React 16, we can now return multiple children elements in a component’s render method using an array of components, elements and/or strings. For example, this is now valid syntax as of React 16:

class App extends Component {
  render() {
    return [
      <Card key="1" />,
      'Just a text node',
      <Card key="2" title="Hello" content="I'm just a card in the world" />
    ];
  }
}

The benefit to being able to return multiple elements is that we don’t have to include superfluous div elements that wrap our elements and clutter the DOM.

And this works just a well in stateless functional components (SFCs):

const App = () => {
  return [
    <Card key="1" />,
    'Just a text node',
    <Card key="2" title="Hello" content="I'm just a card in the world" />
  ];
};

The problem is that the syntax using an array is a little bit awkward, and we need to add a unique key to elements. The solution, which was introduced with React 16.2, is to make use of React Fragments.

Enter React Fragments

Using the Fragment component, we can now accomplish the same without the array syntax and without using keys. Just use the React.Fragment component to wrap your returned elements:

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <React.Fragment>
        <Card />
        Just a text node
        <Card title="Hello" content="I'm just a card in the world" />
      </React.Fragment>
    );
  }
}

We can make the syntax more concise by importing the Fragment component directly:

import React, { Component, Fragment } from 'react';

class App extends Component {
  render() {
    return (
      <Fragment>
        <Card />
        Just a text node
        <Card title="Hello" content="I'm just a card in the world" />
      </Fragment>
    );
  }
}

<> </> Shorthand Syntax

You can achieve the paramount of conciseness by using the new <> </> shorthand syntax:

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <>
        <Card />
        Just a text node
        <Card title="Hello" content="I'm just a card in the world" />
      </>
    );
  }
}

Babel 7, which is still in beta at the time of this writing, is needed for this shorthand syntax to be properly transpiled to the <React.Fragment> equivalent.

The current stable version of Create React App uses Babel 6.x under the hood, so the shorthand syntax won’t work right out of the box. To start using that syntax now, you can use the latest unstable release of react-scripts, which makes use a Babel 7 beta release:

$ yarn add react-scripts@next

Note also that we can add props to the fragment component when using the <React.Fragment> syntax, but not when using the shorthand syntax. For example, if a top-level fragment is returned when iterating over an array, we can add a key prop, but that’s not possible using the shorthand syntax.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Alligator.io

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel