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

  1. Solution

react error

Solution

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.

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

1
2
3
4
5
6
return (
<React.Fragment>
<h2>Heading</h2>
<h3>Sub Heading</h3>
</React.Fragment>
);

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

1
2
3
4
5
6
7
8
import React, { Component, Fragment } from 'react';
...
return (
<Fragment>
<h2>Heading</h2>
<h3>Sub Heading</h3>
</Fragment>
);

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

1
2
3
4
5
6
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.

1
2
3
4
5
6
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 “key” attribute to prevent the key warning for returned lists.

1
2
3
4
return [
<h2>Heading</h2>,
<h3>Sub Heading</h3>
];

Source: https://medium.com/@jmegilman/react-error-adjacent-jsx-elements-must-be-wrapped-in-an-enclosing-tag-32bc21c4434b