Adjacent JSX elements must be wrapped in an enclosing tag

What is "Adjacent JSX elements must be wrapped in an enclosing tag" error?

If you're working with React, you might have encountered the "Adjacent JSX elements must be wrapped in an enclosing tag" error. This error occurs when you try to return more than one element from a component's render method without wrapping them inside a container element.

Example:


render() {
  return (
    <h1>Hello</h1>
    <p>World!</p>
  );
}

In the above example, we're trying to return two elements - an h1 tag and a p tag - without wrapping them inside a container element. This will result in the "Adjacent JSX elements must be wrapped in an enclosing tag" error.

How to fix the error?

To fix the error, you need to wrap the adjacent JSX elements inside a container element such as a div, section or fragment. Here's how:

Method 1: Using a Div Element


render() {
  return (
    <div>
      <h1>Hello</h1>
      <p>World!</p>
    </div>
  );
}

In the above example, we're wrapping the adjacent h1 and p tags inside a div element. This will fix the error.

Method 2: Using a Fragment Element


render() {
  return (
    <>
      <h1>Hello</h1>
      <p>World!</p>
    </>
  );
}

In the above example, we're using a fragment element to wrap the adjacent h1 and p tags. This is a shorthand syntax for creating an empty fragment element.

Method 3: Using a Section Element


render() {
  return (
    <section>
      <h1>Hello</h1>
      <p>World!</p>
    </section>
  );
}

In the above example, we're using a section element to wrap the adjacent h1 and p tags. This is a semantic HTML element that can be used to group related content.

Conclusion

The "Adjacent JSX elements must be wrapped in an enclosing tag" error can be easily fixed by wrapping the adjacent JSX elements inside a container element such as a div, section or fragment. Choose the method that best fits your use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe