How to Implement React Fragments in React

React Fragments allow developers to group multiple child elements together without adding extra, unnecessary nodes to the Document Object Model (DOM). In this article, you will learn why React Fragments are useful, how to implement them using both the standard and shorthand syntax, and how to use them with keys in list rendering.

Why Use React Fragments?

In React, a component can only return a single root element. Historically, developers solved this by wrapping multiple elements in a container <div>. However, this approach often leads to “div soup”—bloated HTML markup that can break CSS layouts (like Flexbox and Grid) and harm accessibility.

React Fragments solve this problem by letting you group elements without rendering a wrapper element in the final HTML.

Method 1: The Standard Fragment Syntax

The standard way to implement a fragment is by importing Fragment from the React library. This method is highly recommended when you need to pass props, such as a key, to the fragment.

import React, { Fragment } from 'react';

function UserList() {
  const users = [
    { id: 1, name: 'Alice', role: 'Admin' },
    { id: 2, name: 'Bob', role: 'Developer' }
  ];

  return (
    <dl>
      {users.map(user => (
        <Fragment key={user.id}>
          <dt>{user.name}</dt>
          <dd>{user.role}</dd>
        </Fragment>
      ))}
    </dl>
  );
}

In the example above, <Fragment> groups the <dt> and <dd> elements together. Because we are mapping over an array, we must provide a unique key attribute. The standard <Fragment> syntax is the only way to pass keys to a fragment.

Method 2: The Shorthand Syntax

If you do not need to pass any attributes or keys to the wrapper, you can use the cleaner shorthand syntax, which looks like empty HTML tags: <> and </>.

import React from 'react';

function ProfileCard() {
  return (
    <>
      <h2>User Profile</h2>
      <p>Welcome back to your dashboard.</p>
    </>
  );
}

This shorthand compiles exactly the same way as the standard <React.Fragment> syntax but keeps your codebase clean and readable. Note that you cannot pass attributes, including key, to the shorthand empty tags.