The Importance of React Fragments and How to Use Them Properly
A common mistake in React development is forgetting to use Fragments when returning multiple elements, which leads to unnecessary DOM nesting or errors. Here’s a comprehensive guide to using Fragments effectively:
Why Fragments Matter
- Avoid unnecessary div soup – Prevents wrapper elements that break semantic HTML
- Maintain proper structure – Critical for components like tables, lists, or flex containers
- Improve performance – One less DOM node to create and manage
- Cleaner CSS – No unintended style inheritance from wrapper divs
How to Use Fragments Correctly
Basic Syntax
function MyComponent() {
return (
<> {/* This is a Fragment */}
<h1>Title</h1>
<p>Description</p>
<button>Click me</button>
</>
);
}
Explicit Fragment Syntax
function MyComponent() {
return (
<React.Fragment>
<h1>Title</h1>
<p>Description</p>
</React.Fragment>
);
}
When You Must Use Explicit Fragments
- When you need keys in lists:
{items.map(item => (
<React.Fragment key={item.id}>
<h2>{item.title}</h2>
<p>{item.description}</p>
</React.Fragment>
))}
- When tooling doesn’t support shorthand (rare in modern setups)
Common Fragment Use Cases
1. Grouping List Items
function Glossary(props) {
return (
<dl>
{props.items.map(item => (
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</React.Fragment>
))}
</dl>
);
}
2. Conditional Rendering
function Notification({ status }) {
return (
<>
{status === 'error' && <ErrorIcon />}
<Message />
{status !== 'loading' && <DismissButton />}
</>
);
}
3. Table Structures
function Table() {
return (
<table>
<tbody>
<tr>
<Columns />
</tr>
</tbody>
</table>
);
}
function Columns() {
return (
<>
<td>Column 1</td>
<td>Column 2</td>
</>
);
}
What to Avoid
1. Unnecessary Fragments
// Bad - Fragment isn't needed here
function SingleElement() {
return (
<>
<OnlyChild />
</>
);
}
// Good
function SingleElement() {
return <OnlyChild />;
}
2. Fragments with Props (Except Key)
// Won't work - Fragments don't accept props
<>
className="group"
id="section"
>
{/* ... */}
</>
Migration Tips
If you’re refactoring old code that uses wrapper divs:
- Search for patterns like:
<div className="[wrapper|container|group]">
{children}
</div>
- Replace with fragments:
<>
{children}
</>
- Remove any wrapper-specific CSS
Tools to Help
- ESLint Rule:
react/jsx-fragments
"rules": {
"react/jsx-fragments": ["error", "syntax"]
}
- VS Code Extension: React Refactor (can convert divs to fragments)
- Prettier: Will format fragments consistently