Thursday, November 28, 2024
Google search engine
HomeLanguagesJavascriptAdjacent JSX elements must be wrapped in an enclosing tag

Adjacent JSX elements must be wrapped in an enclosing tag

If anyone uses multiple HTML elements inside a render method in the React library, it shows an error specifying that Adjacent JSX elements must be wrapped in an enclosing tag. The reason for the error is that when we use the render method it can only take a single HTML element. That means if you have two or more HTML elements back to back in the render method, then it’s not going to work and show an error. So to fix this error one can embed this all HTML element inside a single div element. Anything that goes inside a div will count as a single HTML element.

Syntax : 

ReactDOM.render(
<div>
  // now one can use more than one html 
  // element inside div element.
</div>,
  document.getElementById("root)
 ); 

Example 1: When I use multiple HTML elements inside a render method :

Javascript




import React from 'react';
import ReactDOM from 'react-dom';
  
ReactDOM.render(
  <h1>Geeks For Geeks</h1>
    
<p>Learn Programming </p>
  
  document.getElementById('root')
);


Output: I get an error specifying that  Adjacent JSX elements must be wrapped in an enclosing tag . To fix this error <h1> and <p> tag must be wrapped in a single HTML element like <div> tag . 

Example 2: When I use a single HTML element inside a render method :

Javascript




import React from 'react';
import ReactDOM from 'react-dom';
  
ReactDOM.render(
  <div>
  <h1>Geeks For Geeks</h1>
    
<p>Learn Programming </p>
  
  </div>,
  document.getElementById('root')
);


Output: I get the expected output with no error, as in render method <h1> and <p> tag is wrapped inside a single div HTML element and anything that goes inside a div will count as a single HTML element.

RELATED ARTICLES

Most Popular

Recent Comments