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>
Or better still
<>
<h5>Applying Fragments</h5>
<p>This is a simpler way of doing it</p>
</>
Not using fragments:
<div>
<h5>Not applying Fragments</h5>
<p>This is the casual way of doing it</p>
</div>
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>
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>
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.
Top comments (0)