Fragments
Learn how you can group a list of children and return multiple elements without adding extra nodes to the DOM.
We'll cover the following
Returning multiple children without a surrounding element
Fragments are some sort of a special component and allow us to create valid JSX without leaving visible traces in the rendered markup. They are a solution to the problem of only ever returning a single element at the top in JSX. This is valid JSX:
render() {
return (
<ul>
<li>Bullet Point 1</li>
<li>Bullet Point 2</li>
<li>Bullet Point 3</li>
</ul>
);
}
But this isn’t:
render() {
return (
<li>Bullet Point 1</li>
<li>Bullet Point 2</li>
<li>Bullet Point 3</li>
);
}
In this example, multiple elements are being returned in the render()
method without a
surrounding element, leading to an error. We do not always want to create new elements
though, especially if the surrounding element is found in a parent component and the child element is found in its own component.
On top of that, many elements (such as table
, ul
, ol
, dl
, …) do not allow for div
elements to be used as an intermediary wrapper (ignoring the fact that we would also litter the markup by using divs
). As we are only permitted to ever return a single root element from a component, fragments can be incredibly useful. We could transform our example from above into the following:
render() {
return (
<React.Fragment>
<li>Bullet Point 1</li>
<li>Bullet Point 2</li>
<li>Bullet Point 3</li>
</React.Fragment>
);
}
The rule that every element returned by a loop needs to have a key
prop still holds. By using a fragment, this is still possible. Let’s illustrate this further by examining another slightly more complex yet more realistic example:
Get hands-on with 1200+ tech skills courses.