Forgetting to use React Fragments (<>…)

Loading

When you need to return multiple elements in JSX without adding an extra DOM node, React Fragments (<>...</>) are the perfect solution. Here’s how to properly use them:

The Problem Without Fragments

function Component() {
  return (
    <h1>Title</h1>
    <p>Description</p>  // ❌ Error: Adjacent JSX elements must be wrapped
  );
}

Solution: Using Fragments

1. Short Syntax (Preferred)

function Component() {
  return (
    <>  {/* No extra DOM element created */}
      <h1>Title</h1>
      <p>Description</p>
    </>
  );
}

2. Explicit Syntax (When You Need Keys)

function Component() {
  return (
    <React.Fragment>
      <h1>Title</h1>
      <p>Description</p>
    </React.Fragment>
  );
}

When to Use Fragments

  1. Grouping list items without breaking table/ul structure
   <table>
     <tbody>
       <tr>
         <Columns />  {/* Returns multiple <td> in a Fragment */}
       </tr>
     </tbody>
   </table>
  1. Conditional rendering of multiple elements
   {condition && (
     <>
       <p>First</p>
       <p>Second</p>
     </>
   )}
  1. Returning multiple elements from components

Key Benefits

  • No extra DOM nodes – cleaner HTML output
  • 🏎️ Slightly better performance than wrapper divs
  • 🧩 Better semantic structure when wrapper elements aren’t needed

Common Mistakes to Avoid

  1. Forgetting to import React (only needed for explicit Fragment syntax)
   import React from 'react';  // Not needed for <> syntax
  1. Trying to style fragments (they don’t accept props)
   <> className="my-class" ...  // ❌ Won't work
  1. Overusing fragments when a semantic container would be better
   // Consider this instead:
   <section>
     <h2>Heading</h2>
     <p>Content</p>
   </section>

Pro Tip

Use VS Code’s React Fragments shortcut:

  1. Type <>
  2. VS Code will auto-complete with </>
  3. Your linter will remind you if you forget to close it!

Leave a Reply

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