What is React Fragment in React JS

Share the post

Hello All, In this React JS tutorial, We will learn What is React Fragment in React JS with a detailed explanation. In the last React JS tutorial, We had discussed How to display JSON data to the table format in React JS.

In this React JS tutorial, We will learn What is React Fragment? What is the Syntax of it? Why you should use React Fragment? What is Keyed Fragment? and Example of React Fragment.

So, let’s Start…

What is React Fragment?

React JS introduces a new feature called React Fragment. This React Fragment will allow you to group a list of children without adding extra nodes to the DOM.

now, what does mean of extra nodes? If you want to return multiple elements using the render method inside the component you need to use the <div> tag, this means you need to add extra nodes to the DOM.

So, to avoid that you can use React Fragment.

Syntax of React Fragment

<React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
 </React.Fragment>

Short Syntax of React Fragment

<>
      <ChildA />
      <ChildB />
      <ChildC />  
</>

Why you should use React Fragment?

  • Less Memory
  • Faster Execution
  • If you don’t want to add an extra node to the DOM

What is Keyed Fragment?

Keyed Fragment is used to map a collection to an array of fragments. as <React.Fragment> may have a key. You all may know without the key react will show the key warning in the console.

Example of the keyed fragment:

function Students(props) {
  return (
    <dl>
      {props.items.map(item => (
        <React.Fragment key={item.id}>
          <dt>{item.name}</dt>
          <dd>{item.marks}</dd>
        </React.Fragment>
      ))}
    </dl>
  );
}

Example of the React Fragment

App.js

import React from 'react';
import Subjects from './Subjects';

export default function App() {
  return (
    <table>
      <th> List of Subjects </th>
      <tr>
        <Subjects />
      </tr>
    </table>
  );
}

Subjects.js

import React from 'react';

export default function Subjects() {
  return (
    <React.Fragment>
      <td>English</td>
      <td>Maths</td>
    </React.Fragment>
  );
}

Output

What is React Fragment
What is React Fragment

1 thought on “What is React Fragment in React JS”

Leave a Comment