Building fragments of JSX

Building fragments of JSX

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:

Image description

Image description

The two elements rendered are and . Here’s what they look like when rendered:

Image description
Let’s compare the two approaches now.

Using wrapper elements
The first approach is to wrap sibling elements in

. Here’s what the source looks like

Image description

The essence of this component is the

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:

Image description

Using fragments
Let’s take a look at the WithFragments component, where we have avoided using unnecessary tags:

Image description

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:

Image description

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.


Discover more from Coursity

Subscribe to get the latest posts to your email.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *