Using Fragments in React

January 18, 2019

When rendering multiple adjacent elements in React, you usually get an error saying "Adjacent JSX elements must be wrapped in an enclosing tag". Basically in React, adjacent elements need to always be wrapped with another element.

In the past this created an inconvenience for developers, because you would end up having a div or span element in there that you didn't really need, but only added to be able to wrap adjacent elements.

React Fragments solve this issue by letting you use an element that will not show up in the DOM once rendered:

// Method #1
render() {
  return (
    <React.Fragment>
      Some text.
      <h2>A heading</h2>
    </React.Fragment>
  );
}

// Method #2 (Only in React v16.2.0+)
render() {
  return (
    <>
      Some text.
      <h2>A heading</h2>
    </>
  );
}

More on Fragments