Explain Codes LogoExplain Codes Logo

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

javascript
jsx
react
performance
Alex KataevbyAlex Kataev·Dec 18, 2024
TLDR

To quickly resolve the Parse Error, encapsulate multiple JSX elements in a single tag of <div> or React Fragments, < >. This maintains a single parent element in your returned JSX.

Here's an example within a <div>:

return ( <div> <FirstElement /> {/* Element No. 1, coming in hot! */} <SecondElement /> {/* Element No. 2, ready to mingle! */} </div> );

Or using fragments, < >:

return ( <> <FirstElement /> {/* Not as enclosing as <div>, but still a team player */} <SecondElement /> {/* Free, yet safely wrapped */} </> );

JSX elements er... and why they need an enclosure

React's design philosophy demands that components adhere to a single root element structure. This core restriction enables the efficiency of React's virtual DOM reconciliation. Hence, attempting to return siblings sans wrapping triggers a clash with this principle, resulting in a Parse Error.

Leaning into React.Fragment

Unnecessary <div> additions can often clutter the DOM tree with superfluous nodes. In this instance, React.Fragment serves as a relief pitching in to encapsulate a list of children sans adding extra nodes to the DOM.

Here's an example withReact.Fragment:

return ( <React.Fragment> <FirstChild /> {/* I am the oldest, listen to me */} <SecondChild /> {/* I'm not less important. Okay? */} </React.Fragment> );

You can also use the shorthand <> syntax to achieve the same outcome, rather succinctly.

Conditional rendering, but make it chic

To conditionally render components in the UI, ternary operators are your best bet. Here's the strategy: Use them within the return statement like so: condition ? trueComponent : falseComponent. For complex conditions, consider defining the logic before the return statement for a clean and readable JSX.

Example of ternary operator within JSX:

return ( <> {isLoggedIn ? <UserProfile /> : <LoginButton />} {/* It's like a VIP bouncer for components */} </> );

Enlisting Lists and Keys

When iterating over an array to dispense JSX elements, encase the list in a single tag or fragment and assign a unique key prop to each child. This strategy aids React during rerendering and patching up the virtual DOM efficiently.

return ( <ul> {items.map(item => ( <React.Fragment key={item.id}> <ItemComponent item={item} /> </React.Fragment> ))} </ul> ); /* Secret Santa for components. Everyone gets a unique present called 'key' */

Common JSX Pitfalls And Their Avoidance Strategy

Refrain from the use of direct if-else blocks in JSX. Stick to using conditional expressions or alternatively helper functions to help untangle the complexity.

Example of a helper function:

function renderContent(isLoggedIn) { if (isLoggedIn) { return <UserProfile />; /* Regular at the club */ } else { return <LoginButton />; /* Sorry buddy, no pass, no entry */ } } return <>{renderContent(user.isLoggedIn)}</>; /* Who goes there? */

React 16 — What’s new on the menu?

React version 16 brought in the ability to return arrays of JSX elements, shedding the necessity for extra wrappers. The catch? Each element must carry a unique key.

Example in React 16+:

return [ <FirstElement key="first" />, /* Not just a pretty face, I have a unique id too */ <SecondElement key="second" />, /* Always the bridesmaid, never the bride */ ];

Divs or Fragments: To use or not to use?

While <div> is the commonplace tag for wrapping elements, it can sometimes lead to a bloated, unseemly DOM tree. But that's where React Fragments come to the rescue with a sleek alternative promising better memory efficiency.

Choosing the right Wrapper:

  • Need some CSS styling or DOM measurements? Go for <div>.
  • Want a sleek DOM sans additional nodes? Use <> or React.Fragment.

Enclosures at work — Light, camera, action!

Enclosures are not just about rectifying a syntactical error in JSX. They also play a crucial part in enhancing performance and maintaining the readability and maintainability of your code.

Introducing complex scenarios — Because life isn't always simple

Even with dynamic or complex JSX structures, the golden rule of enclosing elements in a single-root return rings true. This includes complex conditional logic or nested array mapping structures, which should comply with this rule.

A peek under the hood — Transpilation in action

JSX may cause a lot of eye-rolls, but it's not native JavaScript and requires some fancy transformation by a JSX Transformer, like Babel. Knowing what happens under the hood can help you understand and debug better.

Here's an example of React Fragments transpilation:

// Before <>...</> /* JSX, all dolled up */ // After React.createElement(React.Fragment, null, ...); /* After the Babel spa, pure JavaScript beauty */

Handbook for writing performant JSX

  1. Avoid unnecessary DOM depth: Lean towards React Fragments whenever plausible.
  2. Always use key props for dynamic child elements, this prevents unnecessary re-renders.
  3. Stash away complex logic to methods or hooks for a clean and focused render method.