How to Use React Fragment

    May 4, 20259 min read46 viewsUpdated:May 5, 2025
    How to Use React Fragment

    Brief:
    React is a powerful JavaScript library for building user interfaces, and one of its most useful features is the React Fragment. In this comprehensive guide, we’ll explore everything you need to know about React Fragments, including their advantages, limitations, real-world use cases, and performance optimization in React applications.

    What Are React Fragments?

    React Fragments enable returning multiple elements from a parent component, without unnecessary wrapper elements. Before their introduction, developers had to use a parent container element like a <div>, often resulting in excessive nesting, commonly referred to as “div soup.”

    Introduced in React 16.2, Fragments simplify component structure above code, while keeping the rendered output minimal and efficient.

    Syntax of React Fragments

    Fragments can be written in two ways:

    1. Full Syntax:

      import React, { Fragment } from 'react';
      
      function Component() {
        return (
          <Fragment>
            <h1>Title</h1>
            <p>Some text here.</p>
          </Fragment>
        );
      }
      Full Syntax
    2. Shorthand Syntax:

      function Component() {
        return (
          <>
            <h1>Title</h1>
            <p>Some text here.</p>
          </>
        );
      }
      Shorthand Syntax

      The shorthand <></> is more concise and widely used unless attributes like key are needed.

      using extra div

    Why Use React Fragments?

    If you've ever built a React app, you’ve probably found yourself adding extra <div> elements just to wrap multiple components. This can quickly turn into a messy, bloated DOM—often called "div soup." That’s where React Fragments come in. They let you group multiple elements without adding extra nodes to the DOM, making your code cleaner and more efficient.

    1. Keep Your DOM Clean

    Too many unnecessary <div> elements can make your HTML cluttered and harder to read. Fragments help you avoid that by letting you return multiple elements without wrapping them in a redundant <div>.

    2. Improve Performance

    Fewer elements in the DOM mean less memory usage and faster rendering. When your app has too many unnecessary wrapper elements, it can slow things down and make the UI feel sluggish. Fragments help keep things lightweight.

    3. Prevent Invalid HTML

    Some HTML structures have strict rules. For example, a <tr> inside a table must contain <td> or <th>, not a <div>. If you accidentally put a <div> there, your layout might break. Fragments let you wrap elements properly without introducing invalid HTML.

    Why Were React Fragments Introduced?

    Before React Fragments, if you wanted to return multiple elements from a third parent div component, you had to wrap them in a third parent div: <div>. This wasn’t always ideal because:

    • It added unnecessary elements to the DOM.

    • It could mess up layouts (especially in tables or flexbox structures).

    • It could slow down React’s reconciliation algorithm, which is responsible for efficiently updating the UI.

    Now, with Fragments, you can return multiple elements without extra clutter, keeping your code clean and efficient. It’s a small change that makes a big difference!

    Advantages and Limitations of React Fragments

    React Fragments provide a way to group multiple elements without adding extra nodes to the DOM. This helps keep the HTML clean and improves performance. However, they also come with some limitations. Below is a detailed explanation with examples.

    1. Keeps the DOM Clean (Avoids Extra <div> Elements)

    When returning multiple elements from a component, developers often wrap them in a <div>. While this works, it introduces unnecessary elements into the DOM, making the structure more complex than needed.

    Without Fragments (Extra <div> Wrappers)

    function MyComponent() {
      return (
        <div>  {/* Extra div that serves no purpose */}
          <h1>Hello, World!</h1>
          <p>This is a React component.</p>
        </div>
      );
    }
    

    Problem: The <div> does not contribute to the layout or styling, but still exists as an additional node in the DOM. This extra node makes the HTML structure more cluttered than necessary.

    With Fragments (Cleaner DOM)

    function MyComponent() {
      return (
        <>
          <h1>Hello, World!</h1>
          <p>This is a React component.</p>
        </>
      );
    }
    

    Benefit: The component returns multiple elements without adding extra nodes to the DOM, making it more efficient and easier to read.

    2. Improves Performance (Faster Rendering and Lower Memory Usage)

    Every additional element in the DOM consumes memory and affects rendering performance. A cleaner DOM with fewer elements helps optimize the application.

    Example: Rendering Lists More Efficiently

    import React from "react";
    
    // This component returns multiple <li> items using a React Fragment
    function ItemList() {
      return (
        <>
          <li>Item 1</li>
          <li>Item 2</li>
          <li>Item 3</li>
        </>
      );
    }
    
    // Main App component that uses ItemList inside a <ul>
    function App() {
      return (
        <div>
          <h2>My Items</h2>
          <ul>
            <ItemList />
          </ul>
        </div>
      );
    }
    
    export default App;
    Rendering Lists More Efficiently

    Benefit: Since the <ItemList /> component does not introduce an unnecessary <div>, the <ul> remains clean, and the list items remain direct children of <ul>. This improves rendering efficiency.

    3. Maintains Proper HTML Structure (Prevents Invalid Nesting)

    Some HTML elements have strict nesting rules. For example, a <tr> inside a <table> must contain only one element <td> or <th>, and inserting a <div> inside a <tr> is invalid.

    Without Fragments (Invalid HTML)

    function TableRow() {
      return (
        <tr>
          <div>
            <td>Cell 1</td>
            <td>Cell 2</td>
          </div>
        </tr>
      );
    }
    

    Problem: The <div> inside <tr> violates HTML rules and may cause rendering issues in some browsers.

    With Fragments (Valid HTML)

    function TableRow() {
      return (
        <tr>
          <>
            <td>Cell 1</td>
            <td>Cell 2</td>
          </>
        </tr>
      );
    }
    

    Benefit: The <tr> remains valid, as it only contains <td> elements, preserving proper HTML structure.

    4. Supports Keyed Fragments in Lists

    When rendering multiple elements in a list of elements, React requires each item to have a unique key for efficient updates. Fragments support keys, which makes them useful in dynamic lists.

    Using React.Fragment with Keys

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

    Benefit: The <React. Fragment key={item.id}> ensures that React efficiently updates the list when items change, without adding unnecessary <div> wrappers.

    Limitations of React Fragments

    1. No Direct Styling:

    React Fragments (<>...</>) provide a way to group elements without adding extra DOM nodes, making them useful for maintaining clean and efficient component structures. However, they have certain limitations that developers should be aware of.

    Why Can’t You Style a Fragment?

    Since Fragments do not correspond to a physical DOM element, there is no way to apply CSS styles that want to render them directly. Styling typically requires an actual element as a target, whether through class names, inline styles, or external stylesheets. However, because a Fragment does not exist in the final rendered output, there is no selector or other element name for CSS to act upon.

    Example: Attempting to Style a Fragment (Incorrect)

    <>
      <h1 className="title">Hello World</h1>
      <p className="description">This is a paragraph.</p>
    </>

    Here, while .title and .description classes will apply styling to the <h1> and <p>, you cannot apply styles to the Fragment itself.

    2. Workarounds for Styling When Using Fragments

    1) Wrap with a parent element, div element, or span (When Necessary). If styling is required for grouping purposes, consider wrapping the elements inside a <div> instead of a Fragment:

    <div className="container">
      <h1>Hello World</h1>
      <p>This is a paragraph.</p>
    </div>

    The following code snippet allows the .container class to be targeted in CSS.

    2) Use Fragment-Specific Features like the key attributes. While styling isn’t possible, Fragments do accept the key attribute, which can be useful when rendering lists:

    <>
      {items.map((item) => (
        <React.Fragment key={item.id}>
          <h2>{item.title}</h2>
          <p>{item.description}</p>
        </React.Fragment>
      ))}
    </>

    3) Conditional Rendering with Styled Components If you use libraries like styled components, you might conditionally wrap elements inside a styled container when styling is necessary.

    React Fragments are excellent for maintaining a clean and efficient DOM structure, but their lack of a physical presence means they cannot be styled directly. When styling is required, wrapping elements in a <div> or other appropriate HTML element is often the best approach.

    3. No Keys in Shorthand Syntax:

    The shorthand syntax for Fragments (`<>...</>`) does not support keys. If you need to use keys, you must use the full syntax (`<Fragment key={uniqueKey}>...</Fragment>`).

    In React, Fragments (<></>) allow you to group multiple elements without adding an extra node to the DOM. However, when using the shorthand syntax (<>...</>), you cannot assign a key prop per fragment component, which is often necessary when rendering lists.

    Why Keys Matter?

    Keys help React efficiently update and re-render components by identifying which items have changed, been added, or been removed in a list. React may re-render elements inefficiently without a unique key, leading to potential performance issues.

    Limitations of Shorthand Syntax

    The shorthand Fragment syntax (<>...</>) is a cleaner way to group elements, but does not accept attributes, including keys. If you try to add a key to a shorthand Fragment, it will result in an error.

    Solution: Use React.Fragment

    If you need to use a key, switch to the following code full syntax:

    import { Fragment } from "react";
    const items = ["Apple", "Banana", "Cherry"];
    function ItemList() {
      return items.map((item, index) => (
        <Fragment key={index}>
          <p>{item}</p>
        </Fragment>
      ));
    }

    In this example, each Fragment has a key, allowing React to optimize rendering. If you don’t need a key, you can still use the shorthand (<>...</>).

    4. Readability Concerns:

    Overusing Fragments can make your JSX harder to read, especially if you have deeply nested structures.

    While Fragments (<>...</>) help eliminate unnecessary <div> elements and maintain a cleaner DOM, overusing them can sometimes make JSX harder to read and maintain. This is especially true when dealing with deeply nested structures, as the absence of clear wrapper elements can reduce visual clarity.

    1) Lack of Visual Structure

    When the rendering process has multiple elements that are wrapped in Fragments, it may not be immediately clear where a specific section starts or ends, making the JSX harder to scan.

    Example

    <>
      <Header />
      <>
        <Sidebar />
        <>
          <Content />
          <Footer />
        </>
      </>
    </>

    The excessive nesting of Fragments makes it difficult to understand the layout at a glance.

    2)Confusing Debugging and Styling

    Since Fragments do not appear in the DOM, debugging layout issues can be more challenging. Unlike <div> wrappers, Fragments cannot be targeted using CSS, making it tricky when you need container-specific styles.

    3) Loss of Semantic Grouping

    Wrapping related elements in a <section> or <div> often improves readability by giving a clear visual structure. Without these, the JSX may look cluttered, reducing maintainability for larger projects.

    React Fragments are a powerful feature that optimizes the DOM by eliminating unnecessary wrapper elements. However, they also have limitations, including:

    • No direct styling support

    • No key support in shorthand syntax

    • Readability challenges when overused

    By understanding these constraints and using Fragments strategically, developers can create cleaner, more efficient, and maintainable React components.

    When to Use React Fragments

    • When you need to return multiple elements without adding unnecessary <div> wrappers.

    • When you want to keep the DOM structure clean.

    • When working with tables or other strict HTML elements where improper nesting can cause errors.

    • When rendering lists with keys, using <React.Fragment key={key}>.

    When Not to Use React Fragments

    • When you need to apply attributes like className or id (since Fragments do not support them).

    • When using CSS combinators that rely on a direct parent-child structure.

    • When supporting older browsers like Internet Explorer 11, which may not fully support Fragments.

    React Fragments are a valuable feature that helps create cleaner and more efficient React components. However, they are not always the best choice, and understanding their advantages and limitations can help you decide when to use them effectively.

    How to Use React Fragments to Return Multiple Elements?

    To use React Fragments, you can either use the `<Fragment>` component or the shorthand syntax (`<>...</>`). Here’s an example:

    import React from 'react';
    function App() {
      return (
        <>
          <h1>Hello, World!</h1>
          <p>This is a React Fragment example.</p>
        </>
      );
    }
    export default App;

    In this example, the `<>...</>` syntax is used to group the `h1` and `p` elements without adding an extra node to the root element of the DOM.

    When to Use React Fragments?

    React Fragments are particularly useful in the following scenarios:

    1. Returning Multiple Elements:

    When you need to return multiple JSX elements from the render method of a component, but don’t want to add additional nodes and extra nodes to the DOM.

    In React, child components must return a single parent element. However, there are situations where you need a component to return a single element or multiple JSX elements without introducing unnecessary wrapper elements in the DOM. This helps maintain a cleaner structure of app components and avoids redundant <div> elements in child components, often referred to as "div soup."

    Using React Fragments (<></> or <React.Fragment>)

    React provides Fragments to group multiple elements without adding an extra node in the DOM. Fragments allow better performance and cleaner markup.

    Example 1: Using Short Syntax (<>...</>)

    const List = () => {
      return (
        <>
          <li>Item 1</li>
          <li>Item 2</li>
          <li>Item 3</li>
        </>
      );
    };

    Here, the <li> elements are returned together without a wrapping <div>, ensuring a clean DOM structure.

    Example 2: Using <React.Fragment>

    import React from "react";
    const UserInfo = () => {
      return (
        <React.Fragment>
          <h2>John Doe</h2>
          <p>Software Engineer</p>
        </React.Fragment>
      );
    };

    This is useful when you need to pass keys to elements, such as when rendering lists dynamically.

    Why Avoid Extra Wrappers?

    • Prevents Unnecessary DOM Nodes – Keeps the structure minimal.

    • Improves Accessibility – Some extra <div> wrappers can interfere with screen readers.

    • Enhances Styling Flexibility – Avoids disrupting CSS styles or flex/grid layouts.

    Leveraging Fragments, you assure that your JSX remains clean, efficient, and well-structured.

    2. Grouping Elements:

    When you need to group elements without introducing a third parent element or container element.

    When building a user interface, there are situations where you need to group multiple elements without adding an unnecessary third parent element or a container third parent element. This is crucial for maintaining a clean DOM structure, improving accessibility, and preventing layout issues caused by excessive nesting.

    Ways to Group Elements Without a Parent Container

    1) Using React Fragments (<>...</> or <React.Fragment>)

    In React, a common way to group elements without affecting the DOM element or structure is by using Fragments.

    Example:

    <>
      <h2>Product Name</h2>
      <p>Description of the product</p>
    </>
    

    This prevents the introduction of an extra <div>, making the output cleaner.

    2) Using display: contents in CSS

    This allows elements inside a wrapper and parent component to behave as if they were direct children of child components of the wrapper’s parent component.

    Example:

    <div class="group" style="display: contents;">
      <h2>Heading</h2>
      <p>Paragraph</p>
    </div>
    

    The <div> exists above the code, in the parent div, in the markup above code snippet, but does not create a div element or new box in the layout.

    3) Logical Grouping for Accessibility

    While avoiding unnecessary divs is good for performance, sometimes a wrapper is necessary for accessibility (e.g., <section>, <fieldset> in forms).

    Example:

    <fieldset>
      <legend>Contact Information</legend>
      <input type="text" placeholder="Name" />
      <input type="email" placeholder="Email" />
    </fieldset>
    

    These groups form fields meaningfully without relying on a generic <div>.

    By applying these techniques, you can structure child components of your UI efficiently, keeping the DOM lightweight while ensuring accessibility and maintainability of code.

    4) Avoiding Invalid HTML:

    When rendering elements like table cells or list items, using a `div` as a wrapper around html element can result in invalid HTML. Fragments solve this problem.

    When rendering elements like table cells (<td>, <th>) or list items (<li>), wrapping them in a <div> can lead to invalid HTML because certain elements have strict structural requirements.

    For example, inside a <table>, the only valid direct child elements are <thead>, <tbody>, and <tr>. If you use a <div> around a <td>, the browser may ignore or misinterpret it, potentially breaking the layout or causing accessibility issues.

    Example of Invalid HTML:

    <tr>
      <div>
        <td>Row 1, Column 1</td>
        <td>Row 1, Column 2</td>
      </div>
    </tr>
    

    Here, the <div> inside <tr> makes the HTML structure invalid because <tr> should only contain <td> or <th> elements.

    Correct Approach Using Fragments:

    <tr>
      <>
        <td>Row 1, Column 1</td>
        <td>Row 1, Column 2</td>
      </>
    </tr>
    

    Fragments (<>...</>) allow grouping multiple elements without adding an unnecessary wrapper or single element, preserving the correct table structure.

    Similarly, for lists:

    <ul>
      <>
        <li>Item 1</li>
        <li>Item 2</li>
      </>
    </ul>
    

    By using fragments instead of a <div>, we maintain valid HTML and ensure proper rendering.

    Real-World Use Cases for React Fragments

    1. Using React Fragments in Layout Components

    In layout components, you often need to group multiple elements only one element without adding an extra element, an extra node element, or an additional node name. For example:

    function Layout() {
      return (
        <>
          <Header />
          <MainContent />
          <Footer />
        </>
      );
    }

    Here, the `Header`, `MainContent`, and `Footer` components are grouped using a Fragment, avoiding an unnecessary outer div.

    2. Using React Fragments in Conditional Rendering

    When rendering elements conditionally, Fragments can help you avoid adding extra nodes:

    function ConditionalComponent({ isLoggedIn }) {
      return (
        <>
          {isLoggedIn ? <WelcomeMessage /> : <LoginButton />}
        </>
      );
    }

    3. Rendering Arrays with React Fragments

    When rendering arrays, Fragments can help you avoid adding extra nodes:

    function List({ items }) {
      return (
        <>
          {items.map((item) => (
            <Fragment key={item.id}>
              <li>{item.name}</li>
            </Fragment>
          ))}
        </>
      );
    }

    4. Grouping Multiple Elements

    Fragments are ideal for grouping multiple elements and returning them from a component:

    function GroupedElements() {
      return (
        <>
          <h1>Title</h1>
          <p>Description</p>
          <button>Click Me</button>
        </>
      );
    }

    Optimizing Performance with React Fragments

    How React Fragments Improve Performance?

    By avoiding the creation of extra nodes in the DOM, React Fragments can significantly improve render performance. This is especially beneficial when dealing with large arrays of data or complex layouts. Fewer extra DOM nodes mean less memory usage and faster rendering.

    Example: Performance Optimization

    Consider a scenario where you’re rendering a large list of items:

    function LargeList({ items }) {
      return (
        <ul>
          {items.map((item) => (
            <Fragment key={item.id}>
              <li>{item.name}</li>
            </Fragment>
          ))}
        </ul>
      );
    }

    Using Fragments here ensures that no extra nodes are added to the DOM, resulting in better performance.

    How to Export a React Fragment?

    You can export default as a React Fragment as the default for the app component by using the `export default` syntax. This is useful when you want to export default render a Fragment as the main component of your app component with:

    import React from 'react';
    function App() {
      return (
        <>
          <h1>Welcome to My App</h1>
          <p>This is the main component.</p>
        </>
      );
    }
    export default App;

    Benefits of Exporting a Fragment

    Exporting a Fragment as the export default app allows you to take advantage of the benefits of using React Fragments as export default app, such as avoiding extra nodes in export default app and maintaining a clean DOM structure export default app.

    Conclusion

    React Fragments are a powerful tool for React developers looking to optimize their applications. Allowing you to group multiple elements without adding extra nodes to the DOM, Fragments help you maintain a clean and efficient component structure. Whether you’re working on a simple layout or a complex application, React Fragments can improve performance and simplify your code.

    Mastering React Fragments, you can take your React development skills to the next level and build more efficient and maintainable applications. So, start using React Fragments today and experience the benefits for yourself.

    This blog post has covered everything you need to know about React Fragments, from their basic usage to advanced optimization techniques. With this knowledge, you’re well-equipped to use React Fragments effectively in your projects. Happy coding!

    24

    Related articles

    This website uses cookies to analyze website traffic and optimize your website experience. By continuing, you agree to our use of cookies as described in our Privacy Policy.