React fragments explained simply
Getting started
In React, a “fragment” is a structure that enables you to group a list of children elements together without adding extra nodes to the DOM. Fragments are useful when you want to render a list of children without adding an extra wrapper element around the list.
To use a fragment in React, you can use the <React.Fragment>
element, or the shorter <>
syntax. The <React.Fragment>
/ <>
element acts as a placeholder for the list of children, and it does not render any DOM elements itself.
Here’s an example of how you might use a fragment to render a list of items:
import React from 'react';
function MyList({ items }) {
return (
<> // React fragment
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</> // Close fragment
);
}
In this example, the MyList
component uses a fragment to render a list of li
elements without adding an extra wrapper element around the list. The fragment acts as a placeholder for the list of li
elements, and the li
elements are rendered directly in the DOM. The structure of the rendered DOM looks like:
li
li
li
If we didn’t use fragments, we would have to wrap the li
elements with some other parent element (like a div
):
import React from 'react';
function MyList({ items }) {
return (
<div> // Wrap list in a parent div
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</div>
);
}
The DOM structure here looks like:
div
li
li
li
div
With fragments we don’t have to render unnecessary divs, but without fragments we do.