Forgetting to Use React Fragments
When you forget to use React Fragments (<>...</>
) and try to return multiple JSX elements without a wrapper, you’ll encounter the error:
“Adjacent JSX elements must be wrapped in an enclosing tag”
Common Scenarios Where This Happens
- Direct multiple returns:
// ❌ Wrong - will cause error
function Component() {
return (
<h1>Title</h1>
<p>Content</p>
);
}
- Conditional rendering:
// ❌ Wrong
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return (
<Profile />
<LogoutButton />
);
}
return <LoginButton />;
}
How to Fix It
1. Using Fragment Shorthand (Best Solution)
function Component() {
return (
<>
<h1>Title</h1>
<p>Content</p>
</>
);
}
2. Explicit React.Fragment
import React from 'react';
function Component() {
return (
<React.Fragment>
<h1>Title</h1>
<p>Content</p>
</React.Fragment>
);
}
3. For Conditional Rendering
function Greeting({ isLoggedIn }) {
return isLoggedIn ? (
<>
<Profile />
<LogoutButton />
</>
) : (
<LoginButton />
);
}
Why Fragments Matter
- Cleaner DOM: No unnecessary wrapper divs
- Better Performance: Fewer DOM nodes to render
- CSS Friendly: No unexpected layout issues from extra wrappers
- Semantic HTML: Important for tables, lists where extra divs would break structure
Pro Tip: ESLint Rule
Add this to your ESLint config to catch missing fragments:
{
"rules": {
"react/jsx-fragments": ["error", "syntax"]
}
}
This will enforce using either <>...</>
or <React.Fragment>...</React.Fragment>
syntax.