What is React Fragments in React
This article provides a clear and concise guide to React Fragments, explaining what they are, why they are essential for clean code, and how to use them. You will learn how Fragments solve the common issue of unnecessary wrapper DOM elements, explore the different syntaxes available (including the popular shorthand notation), and see practical examples of how they improve your application’s layout and performance.
In React, components must return a single root element. If you want
to return multiple adjacent elements, you would traditionally have to
wrap them in a container element, most commonly a
<div>. While this works, it often leads to “div
soup”—a bloated DOM tree filled with unnecessary wrapper elements that
serve no semantic purpose and can break CSS layouts like Flexbox or
Grid.
React Fragments solve this problem. A Fragment allows you to group a list of children elements without adding an extra, useless node to the HTML DOM. When React renders the component, the Fragment itself disappears, leaving only the child elements in the final HTML output.
How to Use React Fragments
There are two common ways to implement Fragments in your React application: the standard syntax and the shorthand syntax.
1. The Standard Syntax
You can import Fragment from the React library and use
it as a wrapper tag:
import React, { Fragment } from 'react';
function UserProfile() {
return (
<Fragment>
<h1>John Doe</h1>
<p>Software Engineer</p>
</Fragment>
);
}The rendered HTML in the browser will look clean and direct:
<h1>John Doe</h1>
<p>Software Engineer</p>2. The Shorthand Syntax
React also provides a shorter, more concise syntax that looks like
empty tags (<> and </>). This is
the most common way developers use Fragments:
function UserProfile() {
return (
<>
<h1>John Doe</h1>
<p>Software Engineer</p>
</>
);
}This functions exactly the same as the standard
<React.Fragment> syntax but requires less typing.
When to Use the Standard Syntax (Passing Keys)
While the shorthand syntax is convenient, it does not support
attributes. The only attribute that can be passed to a React Fragment is
the key prop, which is required when rendering lists. If
you are mapping over an array and need to return multiple elements per
item, you must use the standard <React.Fragment>
syntax:
function FeatureList({ features }) {
return (
<dl>
{features.map((feature) => (
<React.Fragment key={feature.id}>
<dt>{feature.title}</dt>
<dd>{feature.description}</dd>
</React.Fragment>
))}
</dl>
);
}Key Benefits of React Fragments
- Cleaner DOM: It prevents unnecessary wrappers, keeping the rendered HTML clean, semantic, and easy to debug.
- Better Layout Control: CSS Flexbox and Grid rely on direct parent-child relationships. Extra wrapping divs can disrupt these layouts; Fragments prevent this issue entirely.
- Performance: A smaller DOM tree uses less memory and speeds up page rendering times.