Today I Learned

A Hashrocket project

React Fragments

Ordinarily React requires that each component returns a single child component. Sibling components cannot be returned in the render function:

// Valid
const MyComponent = () => (
  <div>
    <span>Chicken</span>
    <span>and</span>
    <span>Farm</span>
  </div>
);

// Invalid
const MyComponent = () => (
  <span>Chicken</span>
  <span>and</span>
  <span>Farm</span>
);

Sometimes, however, you have no need for the wrapper component and want to just render the siblings. React allows you to do this with the Fragment component, which satisfies the single child requirement without actually rendering a div in the DOM:

import {Fragment} from "react";

// Valid
const MyComponent = () => (
  <Fragment>
    <span>Chicken</span>
    <span>and</span>
    <span>Farm</span>
  </Fragment>
);

// Renders =>
<span>Chicken</span>
<span>and</span>
<span>Farm</span>

Read more about Fragments here: https://reactjs.org/docs/fragments.html

Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.