Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment

The issue:

When we were returning multiple elements from a react component without a container element we got into the following error:

Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment

Following is the code that triggered the error:

return (
   <div>Users</div>
   <ul className="nav navbar-nav">
      <li></li>
   </ul>
)

The reason:

The error is happening because it should be wrapped in a parent element. In our code we are returning two elements simultaneously. When the above JSX code get transformed for the render method, it tries to return twice for two elements. Two return statements in a single function is an error.

The solution

We can solve this issue in multiple ways. The most convenient and recommended approach is:

Solution #1:

Fragment tag can be used to return multiple components from render according to React 16.4.0. Fragments let us group a list of children without adding extra nodes to the DOM.

return (
<React.Fragment>
    <div>Users</div>
    <ul className="nav navbar-nav">
        <li></li>
    </ul>
</React.Fragment>
)

Solution #2:

Array can be used to return multiple components from render according to React 16.0.0.

return ([
    <div>Users</div>,
    <ul className="nav navbar-nav">
        <li></li>
    </ul>
]);

Solution #3:

shorthand syntax (many tools don’t support) can be used to return multiple components from render.

return (
  <>
    <div>Users</div>
    <ul className="nav navbar-nav">
        <li></li>
    </ul>
</>);
Share