Rendering sibling elements in React using Fragments
Tags: react, javascript, webdev
Published: 2019-12-01 19:40:36

---
title: Rendering sibling elements in React using Fragments
published: true
date: 2019-11-26 14:00:02 UTC
tags: react,javascript,webdev 
canonical_url: https://blog.logrocket.com/rendering-sibling-elements-react-fragments/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/17j7ltj1h6tz3bg3jek1.jpeg
---
**Written by [Danny Guo](https://blog.logrocket.com/author/dannyguo/)**✏️

One of the advantages of using React to render a user interface is that it’s easy to break up the UI into components. However, a common problem that arises is when we want to return [sibling](https://javascript.info/dom-navigation#siblings-and-the-parent) elements with no parent. React has a feature called Fragments that provides the solution.

## The problem

If you aren’t familiar with the problem, consider this example.

```jsx
function FAQ() {
    return (
        <p>Q. What is React?</p>
        <p>A. A JavaScript library for building user interfaces</p>
        <p>Q. How do I render sibling elements?</p>
        <p>A. Use Fragments</p>
    );
}
```

This code results in an error: `Adjacent JSX elements must be wrapped in an enclosing tag.`

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## The solutions

One option is to wrap the elements with a parent element.

```jsx
function FAQ() {
    return (
        <div>
            <p>Q. What is React?</p>
            <p>A. A JavaScript library for building user interfaces</p>
            <p>Q. How do I render sibling elements?</p>
            <p>A. Use Fragments</p>
        </div>
    );
}
```

But this method introduces an extraneous element into the DOM, adding an extra level of nesting that we don’t actually need.

React [v16.0](https://github.com/facebook/react/releases/tag/v16.0.0) introduced another option, which is to return an array of elements.

```jsx
function FAQ() {
    return [
        <p>Q. What is React?</p>,
        <p>A. A JavaScript library for building user interfaces</p>,
        <p>Q. How do I render sibling elements?</p>,
        <p>A. Use Fragments</p>
    ];
}
```

Now we need to add commas in between elements. More importantly, this code produces a [key](https://reactjs.org/docs/lists-and-keys.html#keys) warning: `Warning: Each child in a list should have a unique "key" prop.` Adding a key to every element fixes the issue but is quite cumbersome.

```jsx
function FAQ() {
    return [
        <p key="q1">Q. What is React?</p>,
        <p key="a1">A. A JavaScript library for building user interfaces</p>,
        <p key="q2">Q. How do I render sibling elements?</p>,
        <p key="a2">A. Use Fragments</p>
    ];
}
```

React [v16.2](https://github.com/facebook/react/releases/tag/v16.2.0) gave us a cleaner solution, which is to use Fragments.

```jsx
function FAQ() {
    return (
        <React.Fragment>
            <p>Q. What is React?</p>
            <p>A. A JavaScript library for building user interfaces</p>
            <p>Q. How do I render sibling elements?</p>
            <p>A. Use Fragments</p>
        </React.Fragment>
    );
}
```

We no longer need to provide keys, we don’t need to add array commas, and we still avoid adding an extraneous DOM element because `React.Fragment` doesn’t become an actual element during rendering.

We can import `Fragment` to avoid having to fully write out `React.Fragment`.

```jsx
import React, {Fragment} from "react";

function FAQ() {
    return (
        <Fragment>
            <p>Q. What is React?</p>
            <p>A. A JavaScript library for building user interfaces</p>
            <p>Q. How do I render sibling elements?</p>
            <p>A. Use Fragments</p>
        </Fragment>
    );
}
```

However, an even better method is to use the shorthand syntax for Fragments, which looks like empty tags: `<>` and `</>`.

```jsx
function FAQ() {
    return (
        <>
            <p>Q. What is React?</p>
            <p>A. A JavaScript library for building user interfaces</p>
            <p>Q. How do I render sibling elements?</p>
            <p>A. Use Fragments</p>
        </>
    );
}
```

This gives us the same benefits as using `React.Fragment`, but we don’t need to import anything else, and our code looks cleaner.

The only thing that the shorthand syntax doesn’t support for now is adding a `key`. This could be problematic if you are creating a [description list](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl), for example. In this case, use the standard syntax.

```jsx
function Dictionary(props) {
    return (
        <dl>
            {props.terms.map(({word, definition}) => 
                <React.Fragment key={word}>
                    <dt>{word}</dt>
                    <dd>{definition}</dd>
                </React.Fragment>
            )}
        </dl>
    );
}
```

We need to provide a key to avoid a key warning.

In most cases, however, the shorthand method is the best solution for our original problem of returning sibling elements. This solution has worked out well enough that [Vue.js](https://vuejs.org/) will also natively support the concept of Fragments [when v3 is released](https://medium.com/the-vue-point/plans-for-the-next-iteration-of-vue-js-777ffea6fabf).

## Using Fragments

In the last two years, the JavaScript ecosystem has added widespread support for Fragments.

- React added support for the shorthand syntax in [version 16.2.0](https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html) (November 28, 2017)
- [TypeScript](https://www.typescriptlang.org/) added support in [version 2.6.2](https://github.com/Microsoft/TypeScript/releases/tag/v2.6.2) (November 27, 2017)
- [Babel](https://babeljs.io/) added support in [version 7](https://babeljs.io/blog/2018/08/27/7.0.0#jsx-fragment-support) (August 27, 2018)
- [Prettier](https://prettier.io/) added support in [version 1.9](https://prettier.io/blog/2017/12/05/1.9.0.html#jsx-fragment-syntax-3237-https-githubcom-prettier-prettier-pull-3237-by-duailibe-https-githubcom-duailibe) (December 5, 2017)
- [eslint-plugin-react](https://github.com/yannickcr/eslint-plugin-react) added a [jsx-fragments rule](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-fragments.md) in [version 7.12.0](https://github.com/yannickcr/eslint-plugin-react/releases/tag/v7.12.0) (December 28, 2018) to enforce using the standard or shorthand syntax

If you upgrade your dependencies, you will probably be able to use Fragments without any additional configuration.

* * * 
**Editor's note:** Seeing something wrong with this post? You can find the correct version [here](https://blog.logrocket.com/rendering-sibling-elements-react-fragments/).

## Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps
 
![LogRocket Dashboard Free Trial Banner](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)
 
[LogRocket](https://logrocket.com/signup/) is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
[Try it for free](https://logrocket.com/signup/).
* * *
The post [Rendering sibling elements in React using Fragments](https://blog.logrocket.com/rendering-sibling-elements-react-fragments/) appeared first on [LogRocket Blog](https://blog.logrocket.com).