React.Fragment for Grouping Without DOM Nodes
What you'll learn: How to return multiple JSX elements from a component without adding extra wrapper divs to your HTML.
The Problem with Adjacent Elements
You already know from the previous lesson that JSX requires adjacent elements to have a parent wrapper. The naive solution is wrapping everything in a <div>:
function UserCard() {
return (
<div>
<h2>John Doe</h2>
<p>Software Developer</p>
</div>
);
}
But what if that extra <div> breaks your CSS layout? Or clutters your DOM tree with meaningless containers? That's where React.Fragment comes in.
The Solution: React.Fragment
React.Fragment is a special component that lets you group children without adding any actual DOM node:
function UserCard() {
return (
<React.Fragment>
<h2>John Doe</h2>
<p>Software Developer</p>
</React.Fragment>
);
}
When React renders this, the Fragment disappears—only the <h2> and <p> appear in the browser's DOM. It's like an invisible wrapper that satisfies JSX's syntax rules without polluting your HTML structure.
The Shorthand Syntax
There's an even cleaner way to write Fragments using empty tags:
function UserCard() {
return (
<>
<h2>John Doe</h2>
<p>Software Developer</p>
</>
);
}
This <>...</> syntax is just syntactic sugar for <React.Fragment>. Use it whenever you don't need to pass any props (Fragments can accept a key prop, which you'll learn about later).
When to Use Fragments
Think of Fragments like packing materials—they help you ship multiple items together, but you don't want them cluttering up the final product. Use them when:
- Returning multiple elements from a component
- Avoiding unnecessary div wrappers that interfere with flexbox/grid layouts
- Keeping your DOM tree clean and semantic
Key Takeaway: React.Fragment (or <>) lets you group multiple JSX elements without adding extra nodes to the DOM, keeping your HTML structure clean and intentional.