An adapted excerpt from - React and React Native
Fragments are a way to group together chunks of markup without having to add unnecessary structure to your page. For example, a common approach is to have a React component return content wrapped in a
element. This element serves no real purpose and adds clutter to the DOM.Let’s look at an example. Here are two versions of a component. One uses a wrapper element, and the other uses the new fragment feature:
The two elements rendered are and . Here’s what they look like when rendered:
Let’s compare the two approaches now.
Using wrapper elements
The first approach is to wrap sibling elements in
The essence of this component is the
and
tags. Yet, in order to return them from render(), you have to wrap them with
. Indeed, inspecting the DOM using your browser dev tools reveals that does nothing but add another level of structure:Using fragments
Let’s take a look at the WithFragments component, where we have avoided using unnecessary tags:
Instead of wrapping the component content in
, the <> element is used. This is a special type of element that indicates that only its children need to be rendered. The <> is a shorthand for React.Fragment component. If you need to pass a key property to the fragment, you can’t use <> syntax.
You can see the difference compared to the WithoutFragments component if you inspect the DOM:
With the advent of fragments in JSX markup, we have less HTML rendered on the page because we don’t have to use tags such as
for the sole purpose of grouping elements together.Instead, when a component renders a fragment, React knows to render the fragment’s child element wherever the component is used. So fragments enable React components to render only the essential elements; no more will elements that serve no purpose appear on the rendered page.
Top comments (0)