Page Content

Tutorials

What Is Fragments in React.js With Code Example

Fragments in React.js

A fundamental JSX requirement that a function or statement return a single top-level element is addressed by React.js Fragments (also called “empty tags”). Without fragments, you would normally have to wrap several elements in an extra <div> or other container element if you needed to return them from a JSX expression or a component’s render method. This can clog the HTML Document Object Model (DOM).

Fragments in React.js
Fragments in React.js

This is resolved by fragments, which let you group a list of children without introducing additional DOM nodes. **<>…</>** is the syntax for a fragment. These empty tags are removed from the code as React processes it, guaranteeing that no extra HTML elements are presented in the finished product. This keeps the DOM structure flatter and cleaner, which is particularly helpful for layout and styling applications where an additional wrapper could cause issues.

The Problem Fragments Solve

In the past, developers would frequently wrap components in a <div> tag in order to comply with the single-root-element requirement when a component needed to render several items. For instance:

Polluted DOM Structure: The DOM tree may become unduly deep and complex if numerous components contribute an extra <div>, which is an example of a polluted DOM structure.

Styling Issues: When using Flexbox or Grid, where a clear parent-child relationship or particular element structure is essential for appropriate styling, this extra <div> can cause problems with CSS layouts. An intermediary <div> may disturb semantic organisation and styling, for as when rendering <li> elements within a <ul>.

Minor Performance Impact: Adding a lot of superfluous DOM nodes might have a cumulative effect on rendering performance in larger applications, even though it is usually minimal for individual components. By calculating just the necessary modifications, React’s Virtual DOM seeks to minimise expensive DOM operations. Fragments aid in this process by lowering the amount of nodes React must handle before rendering to the actual DOM.

How Fragments Work

This issue is resolved with React Fragments, which let you group a list of children without requiring additional DOM elements. The HTML output is cleaner since the fragment itself is removed when the code comprising it is generated and rendered.

Declaring a React Fragment can be done in two main ways:

Shorthand Syntax (<></>): Declaring a fragment in shorthand syntax (<></>) is the most condensed method. Empty angle brackets are used. For straightforward situations where you only need to group pieces without giving the fragment itself any properties or important props, the shorthand syntax is helpful. Empty tags do not take any HTML properties, as the state.

Explicit Syntax (<React.Fragment></React.Fragment>): When producing lists of fragments, it is frequently necessary to supply a key prop to the fragment, which calls for this more verbose style. You must import React from’react’; in your file as well. Each React.Fragment in this MyListComponent example has a distinct key prop, which is essential for React to update lists effectively.

Benefits of Using Fragments

There are numerous noteworthy benefits to using Fragments in React development.

Cleaner and More Semantic HTML: Fragments make sure that the generated HTML is more similar to the desired semantic structure by avoiding the use of superfluous div wrappers. HTML documents become leaner and easier to read as a result.

Improved CSS Layouts: Developers have more control over their CSS layouts when wrapper divs are not required. This is especially helpful for intricate Grid or Flexbox layouts that need exact element ordering and parent-child relationships to work properly.

Simplified Component Logic: Without having to deal with an additional wrapper element, components may concentrate just on returning the required user interface elements with fragments. This is consistent with React’s tenet of creating apps from modular, tiny components.

No Impact on Component Lifecycle or Props: Fragments are rendering constructs that have no effect on the internal state, props, or lifecycle functions of the component. All they do is make it easier to organise items for rendering.

Code Example:

import React from 'react';
function TableRows() {
  const data = [
    { id: 1, product: 'Apple Watch', price: '₹399' },
    { id: 2, product: 'iPhone 15', price: '₹799' },
    { id: 3, product: 'MacBook Pro', price: '₹1299' },
  ];
  return (
    <>
      {data.map(item => (
        <React.Fragment key={item.id}>
          <tr className="border-b transition-colors hover:bg-gray-50">
            <td className="px-6 py-4 text-left">{item.product}</td>
            <td className="px-6 py-4 text-right font-medium">{item.price}</td>
          </tr>
        </React.Fragment>
      ))}
    </>
  );
}
function App() {
  return (
    <div className="flex items-center justify-center min-h-screen bg-gray-100 p-4">
      <div className="w-full max-w-2xl p-8 bg-white rounded-2xl shadow-xl text-center">
        <h1 className="text-3xl font-extrabold text-blue-800 mb-6">
          React Fragments Table Example
        </h1>
        <p className="text-gray-700 mb-6">
          This table uses fragments to render rows without an extra wrapping `div`.
        </p>
        <div className="overflow-x-auto rounded-lg border">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th scope="col" className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">
                  Product
                </th>
                <th scope="col" className="px-6 py-3 text-right text-xs font-bold text-gray-500 uppercase tracking-wider">
                  Price
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {/* The TableRows component returns multiple <tr> elements here */}
              <TableRows />
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
export default App;

Output:

React Fragments Table Example

This table uses fragments to render rows without an extra wrapping `div`.
Product	        Price
Apple Watch	₹399
iPhone 15	        ₹799
MacBook Pro	₹1299

Conclusion

React.js Fragments offer a straightforward yet effective method of grouping several items without introducing additional DOM nodes, leading to more readable, semantic HTML and better layout control. Fragments improve rendering performance in larger apps, assist maintain leaner DOM structures, and avoid stylistic problems in intricate Flexbox or Grid layouts by removing superfluous wrapper components. Additionally, they streamline component logic by enabling developers to return many elements directly without affecting the lifecycle, properties, or state of the component. Fragments can help create user interfaces that are more effective, maintainable, and aesthetically consistent since they are a lightweight solution that adheres to React’s modular design principles.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index