React Error: Adjacent JSX elements must be wrapped in an enclosing tag

Much like myself and my shattered family relations, React doesn’t like siblings. More specifically, it doesn’t allow siblings in a return function while rendering, and spews the error message: “React Error: Adjacent JSX elements must be wrapped in an enclosing tag.”

React Error: Adjacent JSX elements must be wrapped in an enclosing tag
Me with my favourite siblings

As of React v16.2.0 you can use <React.Fragment> to wrap the sibling elements.


  return (
    <React.Fragment>
      <h2>Heading</h2>
      <h3>Sub Heading</h3>
    </React.Fragment>
  )

Of course, if you import Fragment explicitly, you can just reference <Fragment>.


  import React, { Fragment } from 'react';

const MyComponent = () => {
    return (
      <Fragment>
        <h2 key="heading">Heading</h2>
        <h3 key="subHeading">Sub Heading</h3> 
      </Fragment>;
    )
  };

You can also use the JSX syntax <></> but this requires babel v7 support.


  return (
    <>
      <h2>Heading</h2>
      <h3>Sub Heading</h3>
    </>
  )

Users of previous versions of React can wrap the siblings in a <div> or suitable DOM element.


  return (
    <div>
      <h2>Heading</h2>
      <h3>Sub Heading</h3>
    </div>
  )

If a parent element isn’t suitable and you’re pre version 16.2 (but post version 16), the return can be an array with the DOM elements comma separated, but each element must have it’s own unique “key” attribute to prevent the key warning for returned lists.


  return [
    <h2 key="heading">Heading</h2>
    <h3 key="subHeading">Sub Heading</h3>
  ];

If you can't ensure a unique key (and you're post React v16) you can import 'react-aux', which is simply a wrapper component, much like <Fragment>.


  import Aux from 'react-aux';

const MyComponent = () => {
    return (
        <Aux>
          <h2 key="heading">Heading</h2>
          <h3 key="subHeading">Sub Heading</h3> 
        </Aux>;
    )
  };

If you have any questions or comments or want to connect, you can follow me on Twitter, or sign up to the newsletter in the footer for front-end articles to your inbox 👇


Back home