Select Page

Adjacent JSX elements must be wrapped in an enclosing tag

by | Dec 1, 2023

Adjacent JSX elements must be wrapped in an enclosing tag

The error message “Adjacent JSX elements must be wrapped in an enclosing tag” in React indicates a violation of a key syntax rule. In React, when composing components with JSX, each component’s render method must return a single parent element. This is crucial for React to create a virtual DOM representation of the component.

Consider the following incorrect JSX structure:

// Incorrect
return <h1>Hello</h1>
       <p>World</p>;

In this example, <h1> and <p> are two adjacent JSX elements at the root level, not enclosed within a single parent element. React requires a cohesive structure to represent the component in the virtual DOM.

To address this issue, the JSX elements should be wrapped within a parent element, such as a <div> or <React.Fragment>. Here’s the corrected version using a <div>:

// Correct
return (
  <div>
    <h1>Hello</h1>
    <p>World</p>
  </div>
);

Or using <React.Fragment>:

// Correct with React.Fragment
return (
  <>
    <h1>Hello</h1>
    <p>World</p>
  </>
);

By introducing a parent element, you create a single root for the JSX structure. The choice between <div> and <React.Fragment> depends on your specific use case. <React.Fragment> is particularly useful when you want to avoid introducing unnecessary DOM elements.

This correction ensures that React can properly manage the virtual DOM and maintain the structure of your components, allowing for efficient rendering and updates. Understanding and adhering to this rule is essential for writing valid and well-structured React components.

1 Comment

  1. Regi Salvador

    “Adjacent JSX elements must be wrapped in an enclosing tag” in React indicates a violation of a key syntax rule, and it drove me crazy until I fixed it. Thank you for sharing.

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Looking For Something?

Follow Us

Related Articles

How to Create Custom Hooks in React: Simplified Guide with Examples

How to Create Custom Hooks in React: Simplified Guide with Examples

Heard about custom hooks but not sure how to harness their power? In this blog post, we’ll delve into the wonderful world of custom hooks in React, breaking down what they are, how to create them, and why they’re a game-changer for your projects. What Are Custom...

Understanding Layouts in React

Understanding Layouts in React

If you're someone who works with React, you might think you know what a layout is. But, do you really? React, a popular JavaScript library for building user interfaces, employs the concept of layouts to organize and structure web applications. Despite its widespread...

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join our mailing list to receive the latest news and updates from our team.

You have Successfully Subscribed!