Fragments
Fragments
A lot of components return multiple elements, but React needs one "parent" element returned. It was quite common to wrap elements within a div. Fragments allow you to do this without adding extra nodes to the DOM; which is a really good thing.
There's basically two reasons why you'd use Fragmments; it's a tiny bit faster and uses less memory because React isn't creating an extra node and the DOM inspector is less cluttered with unnecessary divs.
For example, below, we have two ways of rendering the same content.
const items = [
{ id: 1, name: 'SONY 102HB12', description: 'Headphones' },
{ id: 2, name: 'SONY 292LK90', description: 'Microphone' },
]
const ItemDiv = (item) => (
<div key={item.id}>
<dt>{item.name}</dt>
<dd>{item.description}</dd>
</div>
)
// render method ...
<dl>{items.map((item) => ItemDiv(item))}</dl>
Here we populate the DOM with a div, which we use to style the elements admittedly, or we can render it without an additional element and use <> ... </> or <React.Fragment> ... </React.Fragment>.
// Fragment allows us to use key={id} otherwise we could use <> ... </>
import { Fragment } from 'react'
const items = [
{ id: 1, name: 'SONY 102HB12', description: 'Headphones' },
{ id: 2, name: 'SONY 292LK90', description: 'Microphone' },
]
const ItemFragment = (item) => (
<Fragment key={item.id}>
<dt>{item.name}</dt>
<dd>{item.description}</dd>
</Fragment>
)
// render method ...
<dl>{items.map((item) => ItemFragment(item))}</dl>