When to use React.Fragments?

6.5k Views Asked by At

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).

3

There are 3 best solutions below

0
On

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.

0
On

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 <> <\>.

0
On

Using <></> is just bad practice IMO.

I recommend only using <div></div> when you require the children to be placed inside an parent element. Otherwise it is pointless/excess html that is just not required.

For example we have a classname associated with the Div element.

<body>
  <div classname="people-group-1">
    <h1>Hello Shippers</h1>
    <h1>Hello Matey</h1>
    <h1>Hello Pal</h1>
  </div>
  <div classname="people-group-2">
    <h1>Hello Mucka</h1>
    <h1>Hello Geeza</h1>
    <h1>Hello Dude</h1>
  </div>
</body>

I don't recommend using the following example as the Div elements serve no purpose apart from a readability perspective.

<body>
  <div>
    <h1>Hello Shippers</h1>
    <h1>Hello Matey</h1>
    <h1>Hello Pal</h1>
  </div>
  <div>
    <h1>Hello Mucka</h1>
    <h1>Hello Geeza</h1>
    <h1>Hello Dude</h1>
  </div>
</body>

<!-- No different to--->

<body>
 <h1>Hello Shippers</h1>
 <h1>Hello Matey</h1>
 <h1>Hello Pal</h1>
 <h1>Hello Mucka</h1>
 <h1>Hello Geeza</h1>
 <h1>Hello Dude</h1>
</body>

If you need to return multiple elements which dont need a parent, you can use this approach.

import React, { Fragment } from 'react'

const names = ['Shippers', 'Matey', 'Pal', 'Mucka', 'Geeza', 'Dude']

export const Headers = () => (
  <Fragment>{names.map(name => <h1>{`Hello ${name}`}</h1>)}</Fragment>
)

Then you can import it to the renderer of wherever like.

import React from 'react'
import { Headers } from './Headers'

export const Body = () (
  <body>
    <Headers />
  </body>
)

This will transpile into

<body>
 <h1>Hello Shippers</h1>
 <h1>Hello Matey</h1>
 <h1>Hello Pal</h1>
 <h1>Hello Mucka</h1>
 <h1>Hello Geeza</h1>
 <h1>Hello Dude</h1>
</body>