This error occurs when your JSX contains multiple top-level elements without proper wrapping. Here are the solutions:
Primary Solutions
1. Use React Fragments (Recommended)
// Short syntax (preferred)
return (
<>
<Header />
<MainContent />
<Footer />
</>
);
// Full syntax
return (
<React.Fragment>
<Header />
<MainContent />
<Footer />
</React.Fragment>
);
2. Wrap with a DOM Element
return (
<div className="container">
<Header />
<MainContent />
<Footer />
</div>
);
Common Scenarios
3. Conditional Rendering
// Correct approach
return (
<>
{isLoggedIn && <UserMenu />}
<MainContent />
</>
);
// Alternative for complex conditions
return (
<>
{isLoggedIn ? <UserMenu /> : <LoginButton />}
<MainContent />
</>
);
4. Array Returns
// Correct array return
return [
<li key="1">Item 1</li>,
<li key="2">Item 2</li>,
<li key="3">Item 3</li>
];
Advanced Patterns
5. Higher-Order Component Wrapper
const withLayout = (Component) => (props) => (
<div className="layout">
<Header />
<Component {...props} />
<Footer />
</div>
);
6. Custom Grouping Component
const Group = ({ children }) => (
<div className="group" style={{ display: 'contents' }}>
{children}
</div>
);
// Usage
return (
<Group>
<Sidebar />
<Content />
</Group>
);
Best Practices
- Prefer fragments over unnecessary divs to avoid DOM pollution
- Be consistent with your wrapping approach
- Extract complex returns into separate components
- Use meaningful wrappers when semantic structure matters
- Consider CSS alternatives like
display: contents
when appropriate
Common Mistakes to Avoid
- Unwrapped adjacent elements in returns
- Forgetting commas in array returns
- Mixing fragments and arrays inconsistently
- Overusing divs when fragments would suffice
- Nesting ternaries without proper structure
Troubleshooting Checklist
- [ ] Locate the component throwing the error
- [ ] Identify all top-level elements in the return
- [ ] Choose appropriate wrapping strategy
- [ ] Check for proper syntax (especially commas in arrays)
- [ ] Verify all fragments are properly closed
- [ ] Consider component restructuring if needed