When you need to return multiple elements in JSX without adding an extra DOM node, React Fragments (<>...</>
) are the perfect solution. Here’s how to properly use them:
The Problem Without Fragments
function Component() {
return (
<h1>Title</h1>
<p>Description</p> // ❌ Error: Adjacent JSX elements must be wrapped
);
}
Solution: Using Fragments
1. Short Syntax (Preferred)
function Component() {
return (
<> {/* No extra DOM element created */}
<h1>Title</h1>
<p>Description</p>
</>
);
}
2. Explicit Syntax (When You Need Keys)
function Component() {
return (
<React.Fragment>
<h1>Title</h1>
<p>Description</p>
</React.Fragment>
);
}
When to Use Fragments
- Grouping list items without breaking table/ul structure
<table>
<tbody>
<tr>
<Columns /> {/* Returns multiple <td> in a Fragment */}
</tr>
</tbody>
</table>
- Conditional rendering of multiple elements
{condition && (
<>
<p>First</p>
<p>Second</p>
</>
)}
- Returning multiple elements from components
Key Benefits
- ✨ No extra DOM nodes – cleaner HTML output
- 🏎️ Slightly better performance than wrapper divs
- 🧩 Better semantic structure when wrapper elements aren’t needed
Common Mistakes to Avoid
- Forgetting to import React (only needed for explicit Fragment syntax)
import React from 'react'; // Not needed for <> syntax
- Trying to style fragments (they don’t accept props)
<> className="my-class" ... // ❌ Won't work
- Overusing fragments when a semantic container would be better
// Consider this instead:
<section>
<h2>Heading</h2>
<p>Content</p>
</section>
Pro Tip
Use VS Code’s React Fragments shortcut:
- Type
<>
- VS Code will auto-complete with
</>
- Your linter will remind you if you forget to close it!