Forgetting to use React Fragments (<>…)

Loading

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

  1. Direct multiple returns:
// ❌ Wrong - will cause error
function Component() {
  return (
    <h1>Title</h1>
    <p>Content</p>
  );
}
  1. 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

  1. Cleaner DOM: No unnecessary wrapper divs
  2. Better Performance: Fewer DOM nodes to render
  3. CSS Friendly: No unexpected layout issues from extra wrappers
  4. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *