Skip to content

Return multiple elements from a component with React 16

React 16 is here and it brings lots of exciting changes. One of the most requesting features around React community has been returning multiple elements from a component’s render method. Skipping wrapper tag is definitely something that developers are happy about — popularity of my tweet proves this point.

The basic way is to return an array of elements. To avoid warnings you have to add a key to each element, although it may not be needed in the future.

const App = () => [
  <p key="1">React 16 can return multiple elements ❤️</p>,
  <p key="2">React 16 can return multiple elements ❤️</p>,
  <p key="3">React 16 can return multiple elements ❤️</p>,
];

See the Pen 2017-10-02-1 by Pawel Grzybek (@pawelgrzybek) on CodePen.

To avoid array notation and manually added keys to each of the element, you can use an Aux helper function that simply returns all its children. Like so…

const Aux = props => props.children;

const App = () =>
  <Aux>
    <p>React 16 can return multiple elements ❤️</p>
    <p>React 16 can return multiple elements ❤️</p>
    <p>React 16 can return multiple elements ❤️</p>
  </Aux>;

See the Pen 2017-10-02-2 by Pawel Grzybek (@pawelgrzybek) on CodePen.

UPDATE!

React v16.2 introduced another way of returning multiple elements. React.Fragment abstracted in JSX way via just an empty tag. Bare in mind that JSX syntax doesn’t support attributes — use a verbose way if you need so. No extra components needed, no array notation, no keys. Nice!

const App = () => (
  <>
    <p>React 16 can return multiple elements ❤️</p>
    <p>React 16 can return multiple elements ❤️</p>
    <p>React 16 can return multiple elements ❤️</p>
  </>
);

// if your build tool goes crazy, do this…

const App = () => (
  <React.Fragment>
    <p>React 16 can return multiple elements ❤️</p>
    <p>React 16 can return multiple elements ❤️</p>
    <p>React 16 can return multiple elements ❤️</p>
  </React.Fragment>
);

See the Pen 2017-10-02-3 by Pawel Grzybek (@pawelgrzybek) on CodePen.

Nice! Isn’t it?! Find out about more really cool features added in the new version of React in this great Egghead course by Nik Graf.

Did you find it helpful? Consider to hit the share button below to make me more popular than I am! Have a great day you all 🥑