Skip to content
the poor coder

Adjacent JSX elements must be wrapped in an enclosing tag

Poor Man
Published
Reading time
1 min read
On this page

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:#

JavaScript

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

JavaScript

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

JavaScript

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

JavaScript

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC