Forgetting to use React Fragments (<>…)

Loading

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

  1. Avoid unnecessary div soup – Prevents wrapper elements that break semantic HTML
  2. Maintain proper structure – Critical for components like tables, lists, or flex containers
  3. Improve performance – One less DOM node to create and manage
  4. 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

  1. When you need keys in lists:
   {items.map(item => (
     <React.Fragment key={item.id}>
       <h2>{item.title}</h2>
       <p>{item.description}</p>
     </React.Fragment>
   ))}
  1. 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:

  1. Search for patterns like:
   <div className="[wrapper|container|group]">
     {children}
   </div>
  1. Replace with fragments:
   <>
     {children}
   </>
  1. Remove any wrapper-specific CSS

Tools to Help

  1. ESLint Rule: react/jsx-fragments
   "rules": {
     "react/jsx-fragments": ["error", "syntax"]
   }
  1. VS Code Extension: React Refactor (can convert divs to fragments)
  2. Prettier: Will format fragments consistently

Leave a Reply

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