DEV Community

Cover image for Reducing nodes in Dom using Fragment - React js
Samuel Lucas
Samuel Lucas

Posted on

Reducing nodes in Dom using Fragment - React js

I want to create a component but with minimal nodes added to the dom. How do I do that plus what's the effect of extra/unnecessary nodes getting added to the dom?

Hello my dear reader, welcome to today's tips and tricks in React. Briefly, we'll see discussing about React fragment, what it is and how it's used. Enjoy 😊

Fragments let you group a list of children without adding extra nodes to the DOM. - React official website.

React Fragments serve as a cleaner alternative to using unnecessary divs in your code.

Using divs in Fragments place, you tend to get UI malfunctions and unnecessary nodes added to the dom.

The question now is, how do I use it⁉️

import React from "react";
<React. Fragments>
  <h5>Applying Fragments</h5>
  <p>This is a simple way of doing it</p>
</React. Fragments>
Enter fullscreen mode Exit fullscreen mode

Or better still

<>
  <h5>Applying Fragments</h5>
  <p>This is a simpler way of doing it</p>
</>
Enter fullscreen mode Exit fullscreen mode

Not using fragments:

<div>
  <h5>Not applying Fragments</h5>
  <p>This is the casual way of doing it</p>
</div>
Enter fullscreen mode Exit fullscreen mode

When you render the dom for the first two, you get something like this, which is cleaner:

<h5>Applying Fragments</h5>
<p>This is a simple way of doing it</p>
Enter fullscreen mode Exit fullscreen mode

But for that with div, you get something like this, which can cause certain inconsistency in your UI:

<div>
  <h5>Not applying Fragments</h5>
  <p>This is the casual way of doing it</p>
</div>
Enter fullscreen mode Exit fullscreen mode

The difference between the first two, i.e <React. Fragments>...</React. Fragments> & <>...</> is that, just in case you want to pass a key prop maybe after mapping through an array, you can achieve that only with <React. Fragments key={...}>...</React. Fragments> and not the other one.

For more info on React fragment, kindly read the official docs: https://reactjs.org/docs/fragments.html

Have you been using fragments or you're just getting to know if it? Let me know in the comment section.

Kindly drop a like and share if it helped.

Latest comments (0)