Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use React.Fragments?

I just learned about React Fragments.

I understand that fragments are slightly more efficient by creating less tree nodes and makes it cleaner when looking at inspector, but then why should we ever use as containers in React components? Should we always just use React.Fragments in our components?

Will using fragments make it more difficult for styling? (I'm not sure as I haven't tried it out myself yet).

like image 286
yeehuboi Avatar asked Mar 16 '18 23:03

yeehuboi


2 Answers

You can use React.fragments when you have to get props, like, <React.fragments key={1}><\React.fragments>. If you don't need props, you can use <> <\>.

like image 91
Vaishali Avatar answered Nov 13 '22 17:11

Vaishali


In most common practices, React only allows to render single <> element. If you want to render multiple elements, you could surround them by <div></div> or <span></span>.

Fragment situation example: One of the most important usage of Fragment is in the <tbody> tag (as stated in the official website's example Fragment), in a situation that you wanted to render multiple <tr/> rows in an element, you might find that it's impossible to wrap them around <div>, since inside the tag you can only have <tr/> element!

Well, in the other situation, I recommend to always use single element render, unless you have to.

like image 37
user3110146 Avatar answered Nov 13 '22 17:11

user3110146