JSX stands for JavaScript XML. It is a syntax extension of JavaScript that allows us to write HTML-like code in JavaScript. JSX makes it easier to write and add HTML in React. However, when working with JSX, we may encounter an error message that says “Adjacent JSX elements must be wrapped in an enclosing tag”. This error message can be confusing, but it’s actually quite easy to fix.
Why does this error occur?
This error message “Adjacent JSX elements must be wrapped in an enclosing tag” occurs when we have two or more adjacent JSX elements that are not enclosed in a parent element. In simple words, if we have two or more JSX elements that are siblings and not wrapped in a parent element, we will get this error.
How to fix the error
To fix the error “Adjacent JSX elements must be wrapped in an enclosing tag”, we need to wrap the adjacent elements in a parent element. Here’s how we can do it:
- Create a new parent element that will enclose the adjacent elements.
- Wrap the adjacent elements inside the new parent element.
- Make sure that the new parent element is only wrapping the adjacent elements and not any other elements.
Here’s an example of how to fix the error:
// This will throw the error
const App = () => {
return (
<h1>Hello</h1>
<p>World</p>
);
};
// This will resolve the error
const App = () => {
return (
<div>
<h1>Hello</h1>
<p>World</p>
</div>
);
};
In this example, we’ve created a new div
element that wraps the h1
and p
elements.
we can also fix the error by wrapping all the elements in a React Fragment. A React Fragment is a way to group multiple elements together without adding an extra node to the DOM. Here’s how we can use a React Fragment to fix the error:
import React from 'react';
const App = () => {
return (
<React.Fragment>
<h1>Hello</h1>
<p>World</p>
</React.Fragment>
);
};
we can also use a shorter syntax for declaring fragments as below
import React from 'react';
const App = () => {
return (
<>
<h1>Hello</h1>
<p>World</p>
</>
);
};
Conclusion
In conclusion, “Adjacent JSX elements must be wrapped in an enclosing tag” is a common error message that occurs when working with JSX. The error occurs when we have two or more adjacent JSX elements that are not enclosed in a parent element. To fix the error, we need to wrap the adjacent elements in a parent element.
You may also like: