Skip to main content

Why does JSX require a single root element?

Short answer

JSX requires a single root element because a React component must return exactly one value - and JSX compilation turns markup into a call to React.createElement(), which returns a single object (a React element).

If JSX contains several elements at the same level, React does not know what to treat as the function's "main result".


Example of the problem

Error:

javascript
function App() { return ( <h1>Hello</h1> <p>How are you?</p> ); }

Error:

"Adjacent JSX elements must be wrapped in an enclosing tag."

Why? Because this turns into something like:

javascript
return ( React.createElement("h1", null, "Hello"), React.createElement("p", null, "How are you?") );

But return can return only one value, not two elements in a row.


How to do it right

  1. Wrap the elements in a common container:
javascript
function App() { return ( <div> <h1>Hello</h1> <p>How are you?</p> </div> ); }
  1. Or use a fragment (no extra tag in the DOM):
javascript
function App() { return ( <> <h1>Hello</h1> <p>How are you?</p> </> ); }

This is the equivalent of:

javascript
return React.createElement(React.Fragment, null, React.createElement("h1", null, "Hello"), React.createElement("p", null, "How are you?") );

Why does this restriction even exist?

React has to build a component tree (Virtual DOM), and every component must have exactly one "root link".

Otherwise React would not be able to:

  • correctly determine where a component starts and ends;
  • update or remove the component as a whole;
  • attach state and lifecycle to a single node in the tree.

Analogy

Imagine you have a tree:

javascript
App Header Footer

If the App component returned two roots (Header and Footer separately), the tree would end up "with two trunks" - and React would not be able to process them correctly.


Summary

JSX requires a single root element because:

  • return can return only one value;
  • React builds a hierarchical component tree (Virtual DOM);
  • one root guarantees that a component = one node in the tree.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.