Howdy People,😍🙋♀️
I’m on this fantastic journey where I’m exploring new & fun concepts of React.
This concept of Fragments sounds like the perfect
SHORTCUT ever 🤣😂
We all use <div> everytime when we work in html to make containers or wrap elements inside one element.🥱😴
In React JSX,
To return multiple components or elements we have to wrap & group all the elements inside a wrapper like div.
But in most of the cases that div is not required at all & it takes an extra space in the DOM but still we have to use it because that’s how React works.
So, react introduced a new feature in React 16.2 which are React Fragments 🤑🤑🤑
Now React Fragments works exactly like Div, you can wrap or group multiple elements with Fragments.
<React.Fragment>
<MyComponent1 />
<MyComponent2 />
<MyComponent3 />
</React.Fragment>
)
Also you can use Fragments shorthand (<> </>) instead of React.Fragment,
example :
<>
<MyComponent1 />
<MyComponent2 />
<MyComponent3 />
</>
)
But why to use Fragments?? 🤔🤔🤔
Fast
Div element creates a node in DOM & occupy some space, but Fragments doesn’t do any of this.
Less cluttered DOM
Having many nested div makes the DOM large & hard to read or debug but with Fragments, DOM becomes a little easy to look at and debug.
Okay Bye, Hope you liked this shortcut of mine!!
Feel free to add comments & hit likes.
🫡👌⭐💛👍