Runnable lesson · press Try it on the examples to edit and run them here.
A component must return one root element. Sometimes you do not want an extra <div> in the page just to satisfy that rule. A Fragment groups elements without adding anything to the DOM.
Short syntax
function App() {
return (
<>
<h1>Title</h1>
<p>This paragraph and the title are siblings. No wrapper div.</p>
</>
);
}
<> and </> are shorthand for <React.Fragment> and </React.Fragment>.
Why not just a div?
An extra wrapper can break layout and valid HTML. The classic example is a table row:
function Columns() {
return (
<>
<td>Ada</td>
<td>Lovelace</td>
</>
);
}
function App() {
return (
<table>
<tbody>
<tr>
<Columns />
</tr>
</tbody>
</table>
);
}
A <div> inside a <tr> would be invalid HTML and would break the table. The Fragment keeps the cells directly inside the row. The same applies inside flex or grid containers, where an extra wrapper changes the layout.
Fragments with a key
The short syntax cannot take props. When you render a list where each item produces several elements, you need key, so write the long form:
function App() {
const terms = [
{ id: 1, term: "HTML", meaning: "Structure of a page" },
{ id: 2, term: "CSS", meaning: "Style of a page" },
];
return (
<dl>
{terms.map((item) => (
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.meaning}</dd>
</React.Fragment>
))}
</dl>
);
}
key is the only attribute a Fragment accepts (and ref in the newest React versions). See Understanding React Keys for why keys matter.
Importing Fragment
With the modern JSX transform you do not need to import React for <>. If you want the long form, import it:
import { Fragment } from 'react'
<Fragment key={item.id}> ... </Fragment>
When to use a real element instead
If the group needs a class, an id or a style, or it forms a meaningful section (a <section>, a <form>, a <ul>), use that element. Use a Fragment only when you need grouping and nothing else.
Key points
- A Fragment groups children without adding a DOM element.
<>...</>is the short form; use<Fragment key=...>when you need a key.- Prefer a meaningful HTML element when one fits.