Table of contents
1.
Introduction 
2.
React Fragments
3.
Reasons why the 'div' tag is not preferred!
4.
Return Multiple Elements 
5.
Code with Fragment
6.
Conditional Rendering
7.
Rendering of Arrays
8.
Use of React Fragments
9.
Frequently Asked Questions
10.
Key Takeaways
Last Updated: Mar 27, 2024

REACT Fragments

Author Sneha Mallik
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

Working with React components, we come across a term called 'Fragments' which is used frequently. Fragments in React helps us to group a list of children elements without adding the extra nodes to the DOM (Document Object Model). Also, when rendering more than one root element, we place the entire content inside the 'div' tag, which many developers dislike. Hence, in the 16.2 version of React, 'React Fragments' were created, which is used instead of the irrelevant 'div' tag.

Click on the following link to read further: Hooks in React JS

React Fragments

The React fragment is a React component that lets you place two or more items next to each other rather than nested.


To import 'Fragment' in React, we use this:-

import React, {Fragment} from 'React';

 

Before the React 16.2 version, each component was used to return a single element. 

 

If we do not use a 'div' or 'span' tag, all the elements cannot be contained in a single element such as 'span' or 'div.' 
 

Let's see what happens when a single element is not returned,
 

// This will break rather than returning an element
class Application extends React.Component{
    render(){
        return(
            <p>Welcome</p>
            <p>to</p>
            <p>this</p>
            <p>Blog</p>
        )
    }
}

 

Error
 

To solve this issue, we can use the div tag. For example:

// This returns only a single element
class Application extends React.Component{
    render(){
        return(
            <div>
                <p>Welcome</p>
                <p>to</p>
                <p>this</p>
                <p>Blog</p>
            </div>
        )
    }
}

Reasons why the 'div' tag is not preferred!

This can be inconvenient when formatting and positioning the app's layout because each of these extra divs has its own inherited block element styling and characteristics. We will end up manually overwriting all of these properties in the CSS file, which would add to the app's already high number of unnecessary lines of code. Instead of looking for easier ways to strip div components of their properties, we can use the stunning React Fragment component introduced in React 16.2.

Return Multiple Elements 

The most common use case for React fragments is undoubtedly required when we need to return multiple elements. This is simple with React fragments, as the elements do not require a wrapper div.

class App extends React.Component{
    render(){
        return(
            <React.Fragment>
                <Header />
                <Body/>
                <Footer/>
            </React.Fragment>
        );
    }
}

Code with Fragment

Writing the above code using React fragment without using the unnecessary div tag:-

return(
    <React.Fragment>
        <div>Welcome</div>
        <div>to</div>
        <div>this</div>
        <div>Blog</div>
    </React.Fragment>
)

 

We also have a much shorter syntax like this <></>.

return(
    <>
        <div>Welcome</div>
        <div>to</div>
        <div>this</div>
        <div>Blog</div>
    </>
)

Conditional Rendering

When conditionally rendering elements, React fragments can also be used. They make it a lot easier to render groups of elements without having to add any extra markup.

class App extends React.Component{
    render(){
        return(
            <form>
                {this.props.isLoggedIn ? (
                    <React.Fragment>
                        <h3>Hello</h3>
                        <p>You are now logged in!</p>
                    </React.Fragment>
                    ):(
                    <React.Fragment>
                        <h3>Login Here</h3>
                        <label for="username">Username</label><br/>
                        <input type="text" id="username"/><br/>
                        <label for="password">Password</label><br/>
                        <input type="password" id="password"/><br/>
                        <input type="submit" value="Login"/><br/>
                    </React.Fragment>
                )}
            </form>
        );
    }
}

Rendering of Arrays

Because React fragments can have key properties, they can also help us render arrays. Consider the following scenario: you have an array of user objects, and you want to render all of them. You'll need to utilize an element like div to surround the user information because you'll need to set a key prop for each user. However, because React fragments can have key props, you can use React fragments instead and provide them the key prop, eliminating the need for any additional markup.

class Users extends React.Component{
    users = [
        {
            id : 1,
            name:  "John Brian",
            email: "johnbrian34@ctu.gov",
            phone: "+912314214328"
        },
        {
            id : 1,
            name:  "Lexi Almida",
            email: "lexi.almida78@ctu.gov",
            phone: "+912342727287"
        },
        {
            id : 1,
            name:  "Abie Kumar",
            email: "abiekumar129@ctu.gov",
            phone: "+912314214859"
        }
    ];

    render(){
        return(
            <React.Fragment>
                {this.users.map(user => (
                    <React.Fragment key={user.id}>
                        <h3>{user.name}</h3>
                        <p>{user.email}</p>
                        <p>{user.phone}</p>
                    </React.Fragment>
                ))}
            </React.Fragment>
        );
    }
}

Use of React Fragments

The following are the reasons for using the fragment tag:

  • It requires less memory.

It is a little faster and uses less memory (no need to create an extra DOM node). Only huge and deep trees gain from this, although application performance is frequently harmed by death by a thousand cuts. This is a one-cut reduction.

  • When compared to the div tag, it speeds up the code execution.

Some CSS methods, such as Flexbox and CSS Grid, have a unique parent-child relationship, making it difficult to maintain the desired layout while extracting logical components. DOM is like a tree-like structure, so adding more attributes makes it cluttered. But using react fragments, the DOM inspector is more organized and less cluttered. 

So, given that fragments remove the wrapper div, which can cause issues with incorrect HTML and component style and the fact that they are faster and the DOM is less cluttered, I believe they are worthwhile to utilize.

Frequently Asked Questions

  1. What is React.js?

Ans:- React.js is a javascript framework that has greatly simplified the development process. It also provides high-quality React.js applications with intuitive user interfaces. React.js is a popular choice for creating user-friendly and highly engaging websites and applications since it gives developers a variety of options to help them be more creative.

Check out the blog Top 10 React.Js books to enhance your web development skills.

 

2. What do you mean by fragments?

Ans:- The fragment pattern is a React concept that allows a component to return many elements, as demonstrated below. These fragments will enable you to group a list of children without adding any additional nodes to the DOM.

render(){
    return(
        <React.Fragment>
            <ChildElement1/>
            <ChildElement2/>
            <ChildElement3/>
            // We can add a group of child elements from 1-N
            <ChildElementN/>
        </React.Fragment>
    );
}

 

3. What are the advantages of using React?

Ans:- Some of the advantages of using React includes-

  • It is declarative.
  • It is incredibly intuitive and provides interactivity.
  • It is a blend of Javascript and HTML, which simplifies the process of writing the code.
  • It is SEO-friendly which allows you to build excellent user interfaces across various browsers.
  • It handles the dependencies well.

 

4. Do React fragments have keys?

Ans:- Key props can be used in fragments. When we use the normal JSX (JavaScript XML) element syntax to specify a key for a fragment; we cannot use the new <></> syntax. We give a key to a fragment as it allows fragments to be utilized as array items.

 

5. Why do JSX elements have one parent element?

Ans:- When you place two elements next to each other without a parent element, React will warn you that each JSX element must have a parent element. Therefore, the JSX elements must have one parent element.

Key Takeaways

In this blog, we learned about the React concept 'React Fragments' and how to use React Fragment instead of the 'div' tag. We also learned about the rendering of arrays and conditional rendering.
 

Enroll in our Advance Front-end Web Development Course- React.js to deeply understand the concept of React fragments in Web Development with real-life projects to work. To prepare for a React interview, look through the React Interview Questions.
 

Credits: GIPHY

 

Happy Developing!

Live masterclass