Comprender los fragmentos de React (con ejemplos)

React Fragment es un componente React introducido en React v16.2.0. Este componente permite agrupar (o mejor dicho, "emparentar") una lista de componentes React sin añadir un nodo extra al DOM. En el momento de escribir esto, este componente sólo acepta una prop-la prop clave.

ÍNDICE
Molly Floyd
Content & SEO

Why do we use Fragments in React?

In React, JSX expressions must have only one parent element. This syntax is so because JSX is transpiled to JavaScript before execution and only one element—the parent element—can be returned from an expression. This also means that the following code blocks would throw an error:


return (
  <div>Hello</div>
  <div>How are you</div>
)

return (
  <div>
    {isLoading && (
      <span>Text is loading</span>
      <span>Do you see it</span>
    )}
  </div>
)

The first code block would throw an error because there is no parent element before the two child divs. The second one would throw an error because the two span expressions do not have a parent element.

The solution to both blocks would be to add a parent element. This parent element could be a div, a span, or whatever element that is more semantically correct to serve as the parent. However, this would introduce an extra node to the DOM. Sometimes, you may not want that additional node.

Adding extra unnecessary nodes to the DOM can cause one or all of these three things:

  • affect the performance of your application (if there are a lot of them in different parts of your application)
  • produce CSS conflicts if the extra node is not acknowledged in the style declaration
  • affect accessibility in cases where the additional nodes may conflict with your semantic elements

React Fragment was created to solve problems like this, where you do not want to introduce an extra element to the DOM, and you need a parent element.

When should you use React Fragment

You should use the React Fragment when you want to add a parent element to fulfill the JSX syntax, but without introducing an extra node to the DOM.

After compilation, the fragment component does not make it to the DOM—only the children element do.

How to use React Fragments

To access the Fragment component, you can either import it from the React library like this:


import React, { Fragment } from 'react'

or by using the Fragment component on the React object like this:


import React from 'react'

...



I’ll be moving forward with the import method. You can use the Fragment component just the way you use other React components. Here’s an example:


import React, { Fragment } from 'react'

return (
  <Fragment>
    <div>Hello</div>
    <div>How are you</div>    
  </Fragment>
)

Only the div elements make it to the DOM, the Fragment component adds nothing to it.

Examples and Use cases of React Fragment

There are many cases where you may want to use React Fragment instead of adding an extra node. We’ll look at three examples below

1. Using Fragments in a Layout Component

Let’s say you have a Layout component that shows the header, body of a webpage and the footer, you can have this:


<div>
  <Header />
  {children}
  <Footer />
</div>

The div will appear in the DOM, and you can leave it if you want it. But with Fragment, we can write the code as:


<Fragment>
  <Header />
  {children}
  <Footer />
</Fragment>

This way, we do not get an extra unnecessary node in the layout.

2. Using Fragments in Conditional Rendering

Conditional rendering in React is a very common pattern that looks like this:


<div>
  {products.length > 0 ?
    (
      <div>
        <h2>{products.length} products</h2>
        <p>You have {products.length} products in your store</p>
      </div>
    )
  : (
      <div>
        <h2>No products</h2>
        <p>Click here to add a product</p>
      </div>
    )
  }
</div>

In the code above, we have the first element composition which is rendered if the length property of the products is more than 1, else we render the other element composition which shows no products.

The little problem here is we have an outer div, and in the conditional rendering, we have another div. In most cases, you may not need this div so instead of adding it to your DOM, you can use Fragment like this:


<div>
  {products.length > 0 ?
    (
      <Fragment>
        <h2>{products.length} products</h2>
        <p>You have {products.length} products in your store</p>
      </Fragment>
    )
  : (
      <Fragment>
        <h2>No products</h2>
        <p>Click here to add a product</p>
      </Fragment>
    )
  }
</div>

Another way you’d see conditional patterns is the short-circuit conditionals like so:


{products.length < 1 && (
  <Fragment>
    <h2>No products</h2>
    <p>Click here to add a product</p>
  </Fragment>
)}

Only the h2 and p elements will make it to the DOM.

3. Using Fragments to render Arrays

Say you have an array of products and you want to render it on the UI by showing the product’s name as an h2 element and the product details in p or span elements, you may have the following code:


{products.map(product => (
  <h2>{product.name}</h2>
  <p>{product.description}</p>
  <span>{product.price}</span>
))}

As you may have guessed, this isn’t correct JSX. The conditional expression needs a parent element. You may be tempted to add a div but do you really need that in your DOM? If you do, then sure, add a div, but if you don’t, you can add the React Fragment like so:


{products.map(product => (
  <Fragment key={product.id}>
    <h2>{product.name}</h2>
    <p>{product.description}</p>
    <span>{product.price}</span>
  </Fragment>
))}

The Fragment component as stated earlier also accepts the key attribute for which we added a the product’s id as the value. With this, only the h2, p and span elements are added to the DOM.

React Fragment vs div

React Fragment is a component exposed by React which serves as a parent component in JSX but doesn’t add anything to the DOM. The div element on the other hand is an HTML element with no semantic meaning but when used, will be added to the DOM as a node.

React Fragment and div can both serve as parents for grouping children components in a valid JSX syntax. However, only the div can appear on the screen. Only the div accepts classes that you can use to style the container or the children components.

React Fragment only accepts the key attribute which every element, including the div also accepts. But, after compilation, the Fragment component does not get to the DOM, thereby you can not use it on the UI.

React Fragment vs <>

<> is the short syntax of Fragments. Instead of having to type “Fragment” all the time when you need it, you can simply use the empty fragment tag shortcut like this:


<>
  <h1>Hello</h1>
  <p>Hi</p>
</>

You don’t need to import the Fragment component from the React library. You don’t need to import anything new. It’s all valid JSX. And way shorter.

The downside to using this shortcut is that you cannot use the key prop. The key prop is an important prop in React components that keeps React informed of which items have changed, being added or removed in a list. So if you’re working with arrays and you want to use the Fragment component, you have to use the long version of it. But if you only need a parent component somewhere to fulfill JSX syntax without the need for a key prop, then the short syntax is your best shot.

Conclusión

In this article, we’ve seen what React Fragments are, their relevance and three common use cases where this component can be very handy. We also saw its comparison with the div element and also saw a shorter syntax for using Fragments.

It’s good practice to avoid extra DOM nodes with the Fragment component, unless you need them.

Moving forward, you can learn more about Lists and Keys in React.

Añada afiliaciones a su proyecto Webflow en cuestión de minutos.

Más información

Más de 200 componentes Webflow clonables gratuitos. No es necesario registrarse.

Ver biblioteca

Añade membresías a tu proyecto React en cuestión de minutos.

Empezar
¿Qué es Memberstack?

Autenticación y pagos para sitios Webflow

Añada inicios de sesión, suscripciones, contenido cerrado y mucho más a su sitio Webflow: fácil y totalmente personalizable.

Más información
Empezar a construir

Pruebe Memberstack y descubra todo lo que puede crear.

Memberstack es 100% gratis hasta que estés listo para lanzarla - así que, ¿a qué estás esperando? Crea tu primera aplicación y empieza a construir hoy mismo.