Advanced React: React Fragments

Jul 17, 2024

Advanced React: React Fragments

Introduction

  • Topic: React Fragments
  • Purpose: Group list of children elements without adding extra nodes to the DOM

Example 1: Basic Usage

  1. Setup: Create FragmentDemo.js
  2. Create Functional Component: Using rfc snippet to create a functional component
  3. Initial JSX:
    • Text: "Fragment Demo"
    • Included in App.js
  4. Adding More Elements:
    • Convert text to heading using <h1> tag
    • Add a description using <p> tag
    • Error: JSX expressions must have one parent element
    • Solution: Wrap multiple elements in a single parent <div> tag
    • Inspecting DOM: Extra <div> tag is added

Using React Fragments

  • Problem: Unnecessary extra <div> tag in DOM
  • Solution: Replace enclosing <div> with React.Fragment
  • Result:
    • No extra DOM node
    • Multiple elements still returned in JSX

Example 2: Complex Usage in Tables

  1. Setup
    • Create Table.js and Columns.js
  2. Table Component:
    • Replace <div> with <table>
    • Add <tbody> and <tr> for rows
    • Include Columns component
  3. Columns Component:
    • Add two columns: <td>Name</td> and <td>Vishwas</td>
    • Wrap in enclosing <div> due to multiple elements
  4. Problem:
    • Warning: <td> cannot be child of <div>
    • DOM: <td> within a <div> tag
  5. Solution:
    • Replace enclosing <div> in Columns.js with React.Fragment
    • Result: No warnings, no extra <div> in DOM

Advanced Usage

  • Passing Key Attribute:
    • Use case: Rendering list of items
    • Example Code:
      items.map(item => (
        <React.Fragment key={item.id}>
          <h1>Title</h1>
          <p>{item.title}</p>
        </React.Fragment>
      ))
      
    • Note: Only key attribute is allowed currently

Shorthand Syntax

  • Syntax:
    • Replacing React.Fragment with empty <> and </> tags
  • Limitation: Cannot pass the key attribute
  • Example:
    items.map(item => (
      <>
        <h1>Title</h1>
        <p>{item.title}</p>
      </>
    ))
    

Summary

  • React Fragments:
    • Group children elements without extra DOM nodes
    • Use React.Fragment or shorthand <> </>
    • Key attribute allowed in full syntax