← Back to Chapters

React Fragments

? React Fragments

? Quick Overview

React Fragments allow a component to return multiple sibling elements without adding extra nodes to the DOM.

? Key Concepts

  • Components must return a single parent element
  • Fragments avoid unnecessary wrapper elements
  • Cleaner DOM and better layout control
  • Useful in lists and tables

? Without Fragment

? View Code Example
// Component wrapped with unnecessary div
function UserInfo() {
  return (
    <div>
      <h3>Name: Meghraj</h3>
      <p>Role: Developer</p>
    </div>
  );
}

? Using React.Fragment

? View Code Example
// Fragment removes extra DOM wrapper
import React from "react";

function UserInfo() {
  return (
    <React.Fragment>
      <h3>Name: Meghraj</h3>
      <p>Role: Developer</p>
    </React.Fragment>
  );
}

export default UserInfo;

✨ Short Syntax

? View Code Example
// Shorthand fragment syntax
function UserInfo() {
  return (
    <>
      <h3>Name: Meghraj</h3>
      <p>Role: Developer</p>
    </>
  );
}

? Table Rows Example

? View Code Example
// Fragment used for multiple table rows
function TableRows() {
  return (
    <>
      <tr><td>John</td></tr>
      <tr><td>Jane</td></tr>
    </>
  );
}

? Fragments with Keys

? View Code Example
// Keys supported only in React.Fragment
function List() {
  const items = ["Apple", "Banana", "Mango"];
  return items.map((item, index) => (
    <React.Fragment key={index}>
      <h4>{item}</h4>
      <hr />
    </React.Fragment>
  ));
}

? Tips & Best Practices

  • Avoid extra <div> wrappers
  • Use shorthand syntax when keys are not needed
  • Use full Fragment syntax for lists
  • Keeps HTML semantic and clean

? Try It Yourself

  1. Create a component using Fragment
  2. Render multiple table rows using Fragment
  3. Use keys with React.Fragment
  4. Inspect DOM for extra wrappers