React JSX Error – Adjacent tags must be wrapped in an enclosing tag

By Dillon Smart · · · 0 Comments

React

React is a popular and powerful library used by developers across the world. Initially released by Facebook in 2013, React has seen widespread adoption for its faster rendering, stable code and its helpful developer tool set such as the React Developer Tools browser extension for Chrome and Firefox. However, there are a number of reasons why developers who are new to using React may encounter strange, new errors. In this post you will learn, understand and fix the React JSX error ‘Adjacent tags must be wrapped in an enclosing tag’.

What is JSX?

JSX (JavaScript XML) is used in React to allow us, and makes it easier, to write HTML in our React components. JSX prevents the need to create elements in the DOM and eradicates the need for createElement() or appendChild() methods used in traditional HTML/JS webpages.

JSX is not a requirement for React, however using it is highly advisable.

Solution

In React, component tags and elements need to be wrapped in an encapsulating tag.

The wrong way:

return (
   <Component1 />
   <Component2 />
)

That above will give the error Adjacent tags must be wrapped in an enclosing tag.

There are a number of ways to fix this.

Solution 1:

Wrap your components in a <div>

return (
    <div>
        <Component1 />
        <Component2 />
    </div>
)

Solution 2:

Use Reacts Fragment API. This prevents extra nodes being added to the DOM.

return (
    <React.Fragment>
        <Component1 />
        <Component2 />
    </React.Fragment>
)

Solution 3:

Alternatively, you can use the short syntax.

return (
    <>
        <Component1 />
        <Component2 />
    </>
)

Conclusion

Now you have solved the error Adjacent tags must be wrapped in an enclosing tag and know three ways to enclose your tags and components in a React Component.

React JS

0 Comment

Was this helpful? Leave a comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.