Adjacent JSX elements must be wrapped in an enclosing tag

If you’ve started learning React, chances are you’re seeing this error a fair amount:

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

No fear, this one is really easy to solve – with a 100% success rate! Yes, really.

The issue

When returning JSX elements, for example, in your ‘render’ function you need to return one element. That’s what it is expecting. But, I hear you cry, “I want to return more than one thing!”. That’s fine, but you cannot return multiple top-level elements in this way. Say for example you have:

return (  
    <MyLabel />
    <MyField />
)

This will always return the dreaded “Adjacent JSX elements must be wrapped in an enclosing tag”. Unlike other errors in React though, this is a simple one to fix. The error is essentially trying to tell you that you can only return one top level element. In this case we’re returning two. Does it mean you have to split the component up? Not necessarily, although depending on your use case this might be wise. Remember, each component should be broken down as far as possible so that your code is well encapsulated and components can be reused in many circumstances rather than just the specific one you have in mind now.

The fix

At the moment, we’ve got two parents/top-level components – and this just won’t do (in React terms anyway!)

We need to surround our label and field components with another tag. Now you could do this – and indeed many tutorials will tell you to do something like:

return (  
   <div>
    <MyLabel />
    <MyField />
   </div>
)

Now, would this work? Yes. There’s only one parent now – div. However, adding extra elements to the DOM for no reason is definitely discouraged. By the time you are importing many components into a page, you’ll notice the source is getting pretty cluttered.

Fortunately for us, React now allows us to use fragments via the Fragments API. This will ensure that our DOM isn’t getting cluttered with useless divs (divitus anyone?) but also satisfy the need to encapsulated the subcomponents into one parent:

return (  
   <>
    <MyLabel />
    <MyField />
   </>
)

Your label and field (or whatever your two components are) are now safe in a fragment. Your error has disappeared but also you’ve not got an extra div cluttering up the DOM making your job ten times harder – particularly if you’re working on a project of any reasonable size!

Give it a run and watch the error be gone!

You may also like...

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x