Categories
React Answers

How to fix the Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag in React?

Spread the love

The “Adjacent JSX elements must be wrapped in an enclosing tag” error occurs when we have multiple JSX elements next to each other without enclosing them in a single parent element.

JSX expressions must have a single parent element.

Here’s how to fix it:

// Incorrect
render() {
  return (
    <div>Hello</div>
    <div>World</div>
  );
}
// Correct
render() {
  return (
    <div>
      <div>Hello</div>
      <div>World</div>
    </div>
  );
}

In the correct example, both <div> elements are enclosed within a parent <div>, resolving the issue. Alternatively, we can use a React fragment (<React.Fragment>) or an empty tag (<>) as the parent element, especially when we don’t want to add an additional wrapping div to our DOM structure:

// Using React fragment
render() {
  return (
    <React.Fragment>
      <div>Hello</div>
      <div>World</div>
    </React.Fragment>
  );
}
// Using empty tag (shorthand for React fragment)
render() {
  return (
    <>
      <div>Hello</div>
      <div>World</div>
    </>
  );
}

Both of these approaches allow we to group multiple JSX elements without introducing extra divs into the DOM structure. Choose the one that fits best with our component’s structure and readability requirements.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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