React Fragment

Fragment is a powerful feature in React JS that is used to group multiple elements without extra nodes in the DOM. It is very useful to keep your JSX clean and avoid unnecessary elements in the rendered output.

In this tutorial, we’ll cover the concept and usage of React Fragments with clear examples.

Previous Topic – React Render Method

What is React Fragment

React Fragment is a useful feature for creating cleaner and more efficient React components. It will be very helpful when you need to return multiple elements from a component without adding an extra node in the real DOM.

A Fragment can be defined with these syntaxes –

  • React Fragment 
<React.Fragment></React.Fragment>
  • Fragment: 
<Fragment></Fragment>
  • Shorthand React Fragment:
<></>

For example –

Suppose we have created a component named MyBlog and return h1 & p elements by wrapping them with the ‘div’ element.

When you run your app, ‘div’ will be created in DOM as an extra node. Because there is no use of a div element in the DOM. So, It might affect the styling and structure of the web page.

function MyBlog() {
  return (
    <div>
      <h1>Welcome to CodingStatus</h1>
      <p>CodingStatus provides you the best content to learn React Js</p>
    </div>
  );
}

To solve this problem, you can use the React Fragment to group h1 & p elements together without adding an extra ‘div’ element.

function MyBlog() {
  return (
    <>
      <h1>Welcome to CodingStatus</h1>
      <p>CodingStatus provides you the best content to learn React Js</p>
    </>
  );
}

NoteReact Fragment  does not appear in the DOM.

 

<React.Fragment></React.Fragment>

Using <React.Fragment></React.Fragment>, you can group and return multiple elements to the real DOM without adding any extra parent node.

The key point to remember is that React Fragments themselves are not visible in the DOM. Only their children’s elements will be visible. So, It is very useful to keep the HTML structure clean and efficient

Syntax –

<React.Fragment>
// Write  here multiple element
</React.Fragment>

Example –

function MyBlog() {
<React.Fragment> <h2>About CodingStatus</h2> <p>CodingStatus is best blog site to Learn React Coding from Scratch to build an application</p> <h3>CodingStatus Author</h3> <p>Noor Khan</p> </React.Fragment>
}

<Fragment></Fragment>

<Fragment></Fragment> also works similiar to the <React.Fragment></React.Fragment>. But If you want to use <Fragment></Fragment>, then you will have to import Fragment from the React library.

import React, { Fragment } from "react"

Syntax –

<Fragment>
Write multiple element here
</Fragment>

Example –

function MyBlog() {
<Fragment> <h2>About CodingStatus</h2> <p>CodingStatus is best blog site to Learn React Coding from Scratch to build an application</p> <h3>CodingStatus Author</h3> <p>Noor Khan</p> </Fragment>
}

Shorthand React Fragments (<></>)

Shorthand React Fragment is the short form of <React.Fragment></React.Fragment> & <Fragment></Fragment>.

<></> works similar to <React.Fragment></React.Fragment>. But It does not work for attributes or keys. So, This means that you can’t pass attributes or keys to the <></>.

If you need to pass attributes & keys, then you must use the <React.Fragment>

Syntax –

<>
Write here multiple elements
</>

Example –

<>
<h2>About CodingStatus</h2>
<p>CodingStatus is best blog site to Learn React Coding from Scratch to build an application</p>
<h3>CodingStatus Author</h3>
<p>Noor Khan</p>
</>

React Fragments Case Study

Now, Let’s discuss the React Fragment case study and we will understand why should use the React Fragment in React js. Even you will see two examples of group & rendering multiple elements with or without using Fragment.

return() method

Before learning React Fragment, you have to understand the following concept & usage of the return method in React JS.

  • The render() method is used to return a value from a function.
  • You should define the render() method within the React Render Method().
  • The return method can only accept a single element with or without a () bracket.
  • If you need to pass multiple elements, then you have to place them within a parent element such as <div> or react fragment

Render Multiple Elements without React Fragments

If you want to render multiple elements without using the React Fragment, then you can put them with a parent element such as div and pass them to the render() method that should be defined within a render() method.

Note –

  • You will get an error, If you pass multiple elements without any parent elements to the return() method.
  • Parent element will be visible in the DOM
  • return method always considers a parent element as a single element either it contains one or more elements
  • If you need to declare a class name, style, or other attributes except the key attribute, then you should always use the <div> element.
Class Demo extends React.Component {
render(){
 return(
  <div>
  <h1>React Tutorial</h1>
  <p>Learn React Tutorial From Scratch</p>
  <p>Even Create a single web applicatio using React js</p>
   </div>
);
}
}

You can also render multiple items of an order or unorder list without using fragments through a single component.

Class Demo extends React.Component {
render(){
 return(
  <ul>
     <li>HTML</li>
     <li>CSS</li>
     <li>JavaScript</li>
     <li>jQuery</li>
     <li>React js</li>
  </ul>
);
}
}

You can also render multiple rows of a table without using fragments through a single component.

Class Demo extends React.Component {
render(){
 return(
  <table>
     <tr>
        <th>S.N</th>
        <th>Name</th>
        <th>Age</th>
     </tr>
     <tr>
        <td>1</td>
        <td>Noor Khan</td>
        <td>26</td>
     </tr>
     <tr>
        <td>2</td>
        <td>Sunil Kumar</td>
        <td>24</td>
     </tr>
     <tr>
        <td>3</td>
        <td>Aayush Aryan</td>
        <td>28</td>
     </tr>
     <tr>
        <td>4</td>
        <td>Sonali Singh</td>
        <td>22</td>
     </tr>
     <tr>
        <td>5</td>
        <td>Veer Nanda</td>
        <td>21</td>
     </tr>
      
   </table>
);
}
}

Render Multiple Elements with React Fragments

You have seen three examples that render multiple elements covered by a <div>, <ul> & a <table>. Both elements <ul> & <table> have a usage to create a list & table respectively. But a <div> is a useless element that is not good for existing in the DOM. that’s the big problem the making lightweight react applications. So, to solve this problem, React Fragment was introduced which is a very useful feature.

Example –

Class Demo extends React.Component {
render(){
 return(
  <React.Fragment>
  <h1>React Tutorial</h1>
  <p>Learn React Tutorial From Scratch</p>
  <p>Even Create a single web applicatio using React js</p>
  </React.Fragment>
);
}
}

 

Usage of React Fragment

1. To Return Multiple Elements

React components can only return a single element. If you want to return multiple elements, you can use a React Fragment to wrap them.

Example –

import React from 'react';

function MultiElementComponent() {
  return (
    <React.Fragment>
      <h1>Hello</h1>
      <p>Multiple elements!</p>
    </React.Fragment>
  );
}

2. To Assign multiple elements to a variable

You can use React Fragments to group multiple elements and assign them to a variable for later use.

import React from 'react';

function ElementsToVariable() {
  const elements = (
    <React.Fragment>
      <h1>Hello</h1>
      <p>Assign to a variable</p>
    </React.Fragment>
  );

  return elements;
}

4. To render a list of Fragments

You can use React Fragments to render a list of fragments one by one, such as in a mapping operation. Here’s an example:

import React from 'react';

function FragmentList() {
  const items = ['Apple', 'Banana', 'Cherry'];

  return (
    <>
      {items.map((item, index) => (
        <React.Fragment key={index}>
          <p>Fruit:</p>
          <p>{item}</p>
        </React.Fragment>
      ))}
    </>
  );
}

Suggestion

Next Topic – React Component