Handling Multiple Root Elements in JSX
In React, JSX requires that components return a single root element. If you try to return multiple sibling elements without a wrapper, you’ll encounter an error. Here are the solutions:
Solutions
1. Use a Wrapper Div (Traditional Approach)
function Component() {
return (
<div> {/* Single root element */}
<h1>Title</h1>
<p>Content</p>
</div>
);
}
2. React Fragments (Best Solution)
function Component() {
return (
<> {/* Fragment syntax - doesn't create DOM element */}
<h1>Title</h1>
<p>Content</p>
</>
);
}
Or the explicit version:
function Component() {
return (
<React.Fragment>
<h1>Title</h1>
<p>Content</p>
</React.Fragment>
);
}
3. Array Return (With Keys)
function Component() {
return [
<h1 key="title">Title</h1>,
<p key="content">Content</p>
];
}
4. Higher-Order Component
const MultiRoot = ({ children }) => <>{children}</>;
function Component() {
return (
<MultiRoot>
<h1>Title</h1>
<p>Content</p>
</MultiRoot>
);
}
Key Differences
Method | DOM Element Created | Requires Keys | Clean Markup |
---|---|---|---|
Wrapper Div | Yes | No | No |
Fragment (<> ) | No | No | Yes |
React.Fragment | No | No | Yes |
Array Return | No | Yes | No |
Best Practices
- Use Fragments (
<> </>
) for most cases – they don’t add extra DOM nodes - Add keys when returning arrays of elements
- Avoid deep nesting – fragments help keep your DOM structure flat
- Use wrapper divs only when you actually need styling/grouping
Common Pitfalls
- Forgetting to import Fragment when using explicit version:
import React, { Fragment } from 'react';
- Missing keys in array returns (will cause warnings)
- Trying to apply styles/props to fragments (they don’t accept attributes)
- Overusing fragments when a semantic container would be better (like
<section>
or<article>
)
Example Conversion
Before (Error):
function Component() {
return (
<h1>Title</h1>
<p>Content</p> // Error: Adjacent JSX elements
);
}
After (Fixed with Fragment):
function Component() {
return (
<>
<h1>Title</h1>
<p>Content</p>
</>
);
}