How to Fix "JSX element must be wrapped in enclosing tag"
The "Adjacent JSX elements must be wrapped in an enclosing tag" error happens in React, whenever you try to return more than one element from your React component.
// β This will throw the above error
const App = () => {
return (
<h1>Why returning multiple elements from React is invalid.</h1>
<h2>Common React errors</h2>
)
}
To resolve the error, you either need to wrap root sibling elements into a parent element, or you need to use fragments.
// βοΈ Use only one root element
const App = () => {
return (
<div>
<h1>Why returning multiple elements from React is invalid.</h1>
<h2>Common React errors</h2>
</div>
)
}
// βοΈ Even better to use fragments
const App = () => {
return (
<React.Fragment>
<h1>Why returning multiple elements from React is invalid.</h1>
<h2>Common React errors</h2>
</React.Fragment>
)
}
The problem with using a div
element as a wrapper is that you will end up with a bunch of extra DOM elements for no reason. This is why it is preferred to use the built-in React.Fragment
element instead.
Using React.Fragment
will prevent the error, but does not create an extra DOM element. This means you get to keep your markup clean. You may also come across React.Fragment
in the following forms:
import React, { Fragment } from 'react'
// Using only <Fragment />
const App = () => {
return (
<Fragment>
<h1>Why returning multiple elements from React is invalid.</h1>
<h2>Common React errors</h2>
</Fragment>
)
}
// Using a shorthand syntax
const App = () => {
return (
<>
<h1>Why returning multiple elements from React is invalid.</h1>
<h2>Common React errors</h2>
</>
)
}
Whichever format you choose, make sure you keep it consistent across your codebase.
Why React Requires Adjacent Elements to be Wrapped?
Under the hood, React returns React.createElement
function calls from your components. Whenever you try to return multiple sibling elements at the root of your component, you essentially create multiple return
statements.
const App = () => {
return React.createElement('h1')
return React.createElement('h2')
}
Only one return value can be returned from functions, so returning multiple elements is invalid syntax. Subsequent return
statements will be unreachable. This is the reason you must only return one root element from your React components.
You may also return an array of elements, where a fragment may not be applicable. However, this is only on edge cases.
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: