REACT

React Fragment: Syntax, Usage, and Examples

React Fragments allow you to group multiple elements without adding extra nodes to the DOM. This is useful when returning multiple sibling elements from a component without introducing unnecessary wrapper elements. By keeping the DOM clean and avoiding redundant <div> tags, React fragments help improve performance and simplify component structure.


How to Use React Fragments

React provides two ways to use fragments:

  1. Explicit Syntax: Using <React.Fragment>...</React.Fragment>, which allows additional properties like key.
  2. Shorthand Syntax: Using <>...</>, which is cleaner but does not support attributes.

Basic Usage of React Fragments

import React from 'react';

function List() {
  return (
    <React.Fragment>
      <li>Apple</li>
      <li>Banana</li>
      <li>Cherry</li>
    </React.Fragment>
  );
}

Alternatively, you can use the shorthand syntax:

function List() {
  return (
    <>
      <li>Apple</li>
      <li>Banana</li>
      <li>Cherry</li>
    </>
  );
}

Both methods will produce a clean output without adding extra <div> elements around the list items.


When to Use React Fragments

1. Returning Multiple Elements Without a Parent Wrapper

React requires that multiple sibling elements returned from a component be wrapped in a parent element. Instead of using a <div> that adds unnecessary markup, React fragments can be used.

function UserProfile() {
  return (
    <>
      <h2>John Doe</h2>
      <p>Software Developer</p>
    </>
  );
}

Without a fragment, you would have to wrap the elements in a <div>, which could interfere with styles or layout structures.


2. Avoiding Extra DOM Nodes for Performance Optimization

Extra <div> elements increase the size of the DOM tree, which can slow down rendering. Using fragments helps keep the DOM clean, improving performance.

For example, in a <table>, adding an extra <div> inside <tbody> would break the structure. A fragment prevents this issue:

function Table() {
  return (
    <table>
      <tbody>
        <React.Fragment>
          <tr>
            <td>1</td>
            <td>Apple</td>
          </tr>
          <tr>
            <td>2</td>
            <td>Banana</td>
          </tr>
        </React.Fragment>
      </tbody>
    </table>
  );
}

3. Preventing Unintended Side Effects on Styles

When using layout models like Flexbox and CSS Grid, unnecessary wrapper <div> elements can affect alignment and spacing.

Using fragments ensures that only the necessary elements are rendered:

function Card() {
  return (
    <>
      <h3>Title</h3>
      <p>Description</p>
    </>
  );
}

Without a Fragment, an extra <div> could disrupt the layout, making styling more complicated.


Examples of React Fragments in Practice

Using React Fragments in Lists with Keys

When rendering a list, adding a key prop is required to help React track elements efficiently. The shorthand <>...</> syntax does not support keys, so you must use <React.Fragment> instead.

function ItemList({ items }) {
  return items.map((item) => (
    <React.Fragment key={item.id}>
      <h3>{item.name}</h3>
      <p>{item.description}</p>
    </React.Fragment>
  ));
}

If you attempt to use the shorthand syntax (<>...</>), React will throw an error when a key is required.


React Fragment vs. Null in Conditional Rendering

Both React fragments and null can be used to control rendering output, but they serve different purposes:

  • React Fragment: Used when returning multiple elements without adding extra DOM nodes.
  • Null: Used when you don’t want anything rendered.

Example Using React Fragment:

function ShowMessage({ show }) {
  return show ? (
    <>
      <p>Welcome back!</p>
      <p>We missed you.</p>
    </>
  ) : null;
}

Here, if show is false, nothing is rendered.

Example Using Null:

function ShowMessage({ show }) {
  if (!show) return null;
  return <p>Welcome back!</p>;
}

In this case, returning null ensures that no elements are rendered at all.


React fragments in a Table Component

Using fragments is essential when rendering elements inside a <table> to avoid breaking the table’s structure.

function ProductTable({ products }) {
  return (
    <table>
      <tbody>
        {products.map((product) => (
          <React.Fragment key={product.id}>
            <tr>
              <td>{product.name}</td>
              <td>{product.price}</td>
            </tr>
          </React.Fragment>
        ))}
      </tbody>
    </table>
  );
}

Without Fragments, an unnecessary <div> inside <tbody> would cause an invalid table structure.


Learn More About React Fragments

React Fragment vs. Null: Key Differences

  • React Fragments group elements without affecting the DOM structure.
  • Null removes an element from rendering entirely.

Use Fragments when you need to return multiple elements but don’t want a wrapper <div>. Use null when rendering should be skipped entirely.


Adding Keys to React Fragments

Keys are useful when rendering lists to help React optimize re-renders. While regular fragments don’t accept attributes, <React.Fragment> can take a key:

function RenderItems({ items }) {
  return items.map((item) => (
    <React.Fragment key={item.id}>
      <p>{item.name}</p>
    </React.Fragment>
  ));
}

The shorthand <>...</> cannot accept a key, so <React.Fragment key={someKey}>...</React.Fragment> must be used.


The Purpose of React Fragments

React Fragments exist to solve a few common issues in React development:

  1. Avoiding unnecessary <div> elements – Keeps the DOM cleaner.
  2. Improving performance – Reduces memory usage and speeds up rendering.
  3. Maintaining proper structure – Prevents breaking table layouts and other HTML structures.
  4. Preventing CSS issues – Avoids unwanted styling side effects caused by extra wrapper elements.