JSX allows you to nest elements just like HTML, but it has strict parent wrapping rules: every JSX expression must return a single parent (root) element.
This rule ensures React can correctly build and manage the virtual component tree for rendering.
Think of JSX as a tree: there must always be one root node at the top that holds everything else.
JSX looks like HTML, but it is actually syntactic sugar for JavaScript function calls (like React.createElement). For React to work properly, it needs a clean, well-formed tree structure.
That is why every JSX expression (for example, the value returned from a component’s return) must be wrapped in a single parent element such as a <div> or a Fragment.
// ✅ Correct JSX nesting with a single parent <div>
const element = (
<div>
<h1>Welcome</h1>
<p>This is properly nested inside one parent.</p>
</div>
);
// ❌ Incorrect JSX: multiple root elements without a wrapper
const element = (
<h1>Welcome</h1>
<p>This will cause an error!</p>
);
In the incorrect example, the JSX expression tries to return two siblings (<h1> and <p>) at the top level. React expects a single root node, so it throws an error. Wrapping them in a <div> (or Fragment) solves this problem.
Sometimes you want to group elements without adding an extra wrapper like a <div> that would show up in the DOM. React provides Fragments for this purpose.
A Fragment lets you satisfy the “single parent” rule while keeping the DOM clean.
// ✅ Using a Fragment to group elements without extra DOM nodes
const element = (
<>
<h2>Hello</h2>
<p>This is grouped using a Fragment.</p>
</>
);
<div> elements (no “div soup”).JSX nesting is not only about HTML-like tags. You can also nest custom components to build complex UIs from small, reusable pieces.
// ✅ Nesting custom components inside a single parent
function Header() {
return <h1>App Header</h1>;
}
function Content() {
return <p>Main content area</p>;
}
function App() {
return (
<div>
<Header />
<Content />
</div>
);
}
The App component returns one root <div> that contains two child components: <Header /> and <Content />. React creates a clean tree where App → div → Header + Content.
<div> or Fragment).In real React apps, it is common to wrap whole sections of UI with a single layout component or container:
// ✅ Typical layout pattern with a single root wrapper
function App() {
return (
<main>
<header>My Site</header>
<section>Page content goes here</section>
<footer>Footer info</footer>
</main>
);
}
The entire layout is wrapped in one <main> element, which becomes the root of the JSX tree for this component, while the nested elements create the structure inside it.
<></> Fragments when you do not need extra HTML wrappers.Header and Footer.App component using a single <div> or Fragment.<nav> or <main> section inside App.Goal: Understand how JSX enforces proper nesting, why a single parent wrapper is required, and how Fragments help you group multiple child elements without adding extra DOM nodes.