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.

Oldest comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!