React Fragment

Learn via video courses
Topics Covered

Overview

React is a strong library that makes use of previously created components and reuses them as needed. Before React v16, we had to enclose our elements in a div anytime we wanted to return a collection of components or elements. Any component of yours with multiple children would always need a wrapper because React lacked the tools to avoid this, therefore an additional DOM node is necessary.

Introduction

When we were required to return several elements, they had to be contained within a single div prior to the release of React version 16.2. Due to the fact that React components can only return one element at a time, the wrapper div is frequently "irrelevant" and is only used in this circumstance. This practice causes a number of issues, including the rendering of ineffective markup and occasionally even invalid HTML, which is frequently problematic. The Fragments API is useful in this situation.

The syntax known as fragments enables us to add several components to a React component without having to add an additional DOM node for each one. Small React applications are not greatly impacted by this, but working on a real-world project with many nested layers of children can significantly impact the application's response time.

In React, you must call a render method inside the component whenever you wish to display something on the screen. A single element or a collection of elements may be returned by this render method. Only one root node inside it will ever be rendered at a time via the rendering technique. However, the render function will require a 'div' tag and place the entire content or elements inside it if you wish to return several elements. The addition of this extra node to the DOM might occasionally cause your HTML output to be formatted incorrectly, and many developers dislike it.

Example

React introduced Fragments in version 16.2 and later addressed this issue. A list of children can be grouped using fragments without adding more nodes to the DOM.

Syntax

Example

Why Use Fragments?

Because each node in React's tree-like structure represents an element or component, employing a div to surround a group of elements adds a new node, deepening the DOM Tree.

Take a look at the example below, where there are just two children for each React element:

react dom tree

The number of nodes in the DOM Tree at a particular depth is 2d12^d -1. To represent this structure in a conventional application, we just need to be worried about 2d22^d - 2 nodes being present in the DOM.

In contrast, prior versions added an extra node every time we had to use div as a wrapper, which resulted in an additional 2d122^{d-1} - 2 nodes where d is the depth of the DOM Tree.

Let's look at d = 5. Traditionally, we employ 31 nodes or 2d12^d-1 node.

We must use 2d1+(2d12)=452^d -1 + (2^{d-1} -2) = 45 nodes in older versions of React. As a result, we are saving an extra 14 nodes (45 minus 31). Although this may not seem like much, the added benefit of preserving more nodes also grows as the depth of the tree increases.

It keeps 45 nodes from being rendered in the DOM for us! In a very complicated application with several requirements, this provides tremendous performance gains. We are avoiding having 45 nodes shown in the DOM, thanks to it! A very sophisticated application requiring numerous DOM nodes will gain greatly in terms of performance from this.

So basically, The main reason to use the Fragments tag is:

It makes the execution of code faster as compared to the div tag. It takes less memory.

As demonstrated in the code in the above section, in order to render more than one root element, the entire content must be contained within the 'div' tag, which is disliked by many developers. As a result, we employ Fragments that were added in React 16.2 instead of the unnecessary 'div' element.

Syntax

Example

Open App.js and replace the code with the below code.

Output

output use of fragments tag

So, basically, react fragments serve as a cleaner alternative to using unnecessary divs in our code. These fragments don't generate any extra DOM elements, hence the child components of a fragment will render without any wrapping DOM nodes.

We may group several siblings components using React fragments without adding extra markup to the output HTML.

Shorthand Fragment

The initial code and the code above produce identical results, but the main benefit of utilizing it is that it is a little bit quicker than the code that includes the 'div' tag because no DOM nodes were created. It also uses less RAM. Another shortcut for the aforementioned procedure is to use <> and </> in place of "React.Fragment."

The shorthand syntax does not accept key attributes; in that case, you have to use the <React.Fragments> tag.

Syntax

Example

Open App.js and replace the code with the below code.

example of reactfragments tag

Usage

In React, rendering many sibling components dynamically is a frequent approach. We must preserve the HTML element's tree structure when returning JSX from a React component. Only one top-level node may be returned by the component. We are able to solve this issue pretty effectively because of fragments.

React components can only render one element at a time, so it's standard practice to group numerous elements together in a single root element, typically a div wrapper.

Although an additional DOM element can sometimes be added, this workaround is effective in the majority of situations. Think about the elements below and the resulting HTML.

HTML

React Component

If we wrap the <td> elements in a <div>, this will add a <div> element in the middle of <tr> and <td> and break the parent-child relationship.

In order to correctly render the HTML, <Column/> must return multiple <td> elements without any extra element in between the <tr> and <td> tags.

Solution

Multiple elements can be wrapped using React Fragments without the need for an additional DOM element.

In this instance, we do it by substituting the Fragment element in the <Column/> component for the <div> wrapper:

You can also use the short syntax for React Fragments, which are simply empty tags:

Implementation

Index.js

Table.js

Output

Short Syntax

Declaring fragments now has a new, more concise syntax. It appears to be empty tags:

You can use <></> the same way you’d use any other element, except that it doesn’t support keys or attributes.

Key Fragments

The key characteristics are not accepted by the abbreviated syntax. For example, to generate a description list, you need a key to map a collection to an array of fragments. If keys must be provided, you must explicitly specify the fragments with the <React.Fragment> syntax.

In ReactJS, Key is the only attribute that can be passed with the Fragments, as it is needed for mapping a collection to an array of fragments.

Note: The key is the only attribute that can be passed with the Fragments.

Example

Users can develop code that is more understandable, maintainable, and cleaner using react fragments. They don't completely replace divs, but they provide a better method for organizing and presenting all DOM markup overall than divs. By using fragments, we may prevent problems that cause layouts to break and possibly reduce the time it takes for markup to render.

React fragments assist group together several elements or components since they are more efficient, but they should only be utilized when necessary. Use a div in place of a wrapper if JSX style is required.

React Fragment Vs Div

With the help of the fragment syntax, we can add numerous elements to a React component without having to add an additional DOM node for each one.

Let's examine the code in question:

It's a straightforward React component. We can avoid wrapping the JSX in another wrapper element, as seen above when we return only one JSX in a component; however, if we add many JSX elements.

There will be a SyntaxError. Resulting in the crash of our under-development application.

In order for the code to function in React, when a component returns many components, we must wrap them in a container element like div:

While this is fine, it may, however, cause unintended issues in our components.

If div containers are used for anything like adding styles to the JSX, then there is no issue. They are not necessarily required, though, to wrap our JSX. In this instance, when we do, they turn into additional nodes and clog the DOM tree.

When dealing with nested components, these wrappers can occasionally lead to coding anomalies. For instance, when using CSS Flexbox and Grid, the div can cause the layout to malfunction. We may also experience invalid HTML for elements that must follow a specific structure like ul to li and table to tr (table row) to td (table data).

Conclusion

So, in this article, we have learned that you can build more understandable, maintainable code by using fragments. They don't take the place of divs in your HTML, but if you find that your code contains a lot of unneeded divs, they provide a better method for organizing and presenting your content.

Our learning flow has covered the following topics:

  • Why do we use react fragments?
  • Shorthand fragment
  • Usage of react fragment
    • Solution
    • Implementation
  • Short syntax for our react fragments.
  • What are keyed fragments in react.
  • Difference between react fragment and HTML div elements.