Sub topic 5
Returning multiple elements with fragments
This chapter assumes you can write a function component, use JSX expressions in curly braces, pass props, and render lists with map. It also assumes you know basic HTML elements such as dl, table, and ul. You should be comfortable with ES module imports.
The single-root rule
A component returns one value. In JSX, that value is one element. If you try to return two sibling elements, the compiler reports a syntax error.
function Row({ label, value }) {
// Syntax error: adjacent JSX elements must be wrapped
return (
<dt>{label}</dt>
<dd>{value}</dd>
);
}The reason is plain JavaScript. A return statement returns one expression, and each JSX element compiles to one function call. Two adjacent calls with no operator between them are not a valid expression. The chapter on what JSX compiles to covers this in more detail.
Why a wrapper `div` is often wrong
The obvious fix is to wrap the siblings in a div. That works in many places, but it adds a real element to the DOM, and that element can cause problems.
function Row({ label, value }) {
return (
<div>
<dt>{label}</dt>
<dd>{value}</dd>
</div>
);
}A div inside a dl is allowed by the current HTML specification, but a wrapper is invalid or harmful in other places:
- Tables. A
trmay contain onlytdandthcells. Adivbetweentrandtdis invalid, and browsers may move it out of the table. - Lists. A
ulshould containlielements as direct children. - CSS layout. In a flex or grid container, a wrapper becomes the item instead of its children, so the layout changes.
- Selectors. Child selectors such as
.list > listop matching. - Size. Extra wrappers add nodes, which makes the DOM harder to read in developer tools.
A fragment avoids all of these. It groups elements in your code and leaves nothing behind in the DOM.
Fragment syntax
React provides a Fragment component. It has a short form, <>...</>, which needs no import.
function Row({ label, value }) {
return (
<>
<dt>{label}</dt>
<dd>{value}</dd>
</>
);
}If Row is rendered inside a dl, the DOM contains dt and dd as direct children of the dl. No wrapper appears.
The parentheses after return are not part of the fragment. They stop JavaScript's automatic semicolon insertion from ending the statement after return when the JSX starts on the next line.
The long form: `<Fragment>`
The short form cannot take any attributes, including key. When you need a key, import Fragment and write the long form.
import { Fragment } from 'react';
function Glossary({ terms }) {
return (
<dl>
{terms.map((term) => (
<Fragment key={term.id}>
<dt>{term.name}</dt>
<dd>{term.definition}</dd>
</Fragment>
))}
</dl>
);
}Each iteration of map returns two elements, so each iteration needs a grouping. A div would be invalid HTML structure in some contexts and would break dl styling in others. The keyed Fragment solves this.
Put the key on the outermost element returned from the map callback. Here that is the Fragment. Keys on the inner dt and dd would not help, because React compares the items in the array, and the array items are the fragments.
A short-form fragment inside map triggers a warning about missing keys, and the short form has no way to fix it. Use the long form in that case.
Where fragments appear in practice
Fragments are most useful in these cases:
- Component output that must fit a strict parent. Table rows, definition lists, and select options.
- Components that return a header, a body, and a footer. The parent decides how to lay them out.
- Conditional groups. A condition can show or hide several elements at once.
- Keyed groups in lists. As in the glossary example.
Here is a table example where a wrapper would be invalid.
function Columns() {
return (
<>
<td>Name</td>
<td>Role</td>
</>
);
}
export default function App() {
return (
<table>
<tbody>
<tr>
<Columns />
</tr>
</tbody>
</table>
);
}And here is a conditional group.
function Notice({ error }) {
return (
<>
<h2>Status</h2>
{error && (
<>
<p role="alert">{error.message}</p>
<button type="button">Retry</button>
</>
)}
</>
);
}The inner fragment lets the && operator return both elements as one value. When error is null, && short-circuits and nothing is rendered for that slot.
What a fragment is at runtime
The short form is only syntax. The compiler rewrites it into a call that uses the Fragment symbol exported by React. With the automatic runtime, a fragment with two children compiles roughly to this:
import { Fragment as _Fragment, jsxs as _jsxs, jsx as _jsx } from 'react/jsx-runtime';
// Source: <><dt>Term</dt><dd>Meaning</dd></>
const element = _jsxs(_Fragment, {
children: [
_jsx('dt', { children: 'Term' }),
_jsx('dd', { children: 'Meaning' }),
],
});A fragment is a React element whose type is Fragment. When React commits the result to the DOM, it creates the children and skips the fragment itself. The fragment exists in React's tree and never in the browser's DOM.
The short form needs a compiler that understands it. Current tools such as Babel, TypeScript, SWC, and esbuild do. If an old toolchain rejects <>, update it, or use <React.Fragment> as a workaround.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "Adjacent JSX elements must be wrapped in an enclosing tag" | Two sibling elements returned with no parent | Wrap them in `<>...</>` |
| Warning: each child in a list should have a unique "key" prop | Short-form fragment returned from `map` | Use `<Fragment key={...}>` |
| `key` on `<>` is a syntax error | The short form accepts no attributes | Import `Fragment` and use the long form |
| `Fragment is not defined` | Used `<Fragment>` without importing it | `import { Fragment } from 'react'` |
| Layout breaks after refactoring | A `div` wrapper became the flex or grid item | Replace the `div` with a fragment |
| Fragment returns nothing visible | Children are `null`, `false`, or `undefined` | Check the conditions that produce the children |
Decision criteria
Choose a fragment when the grouping has no meaning for the page. Choose a real element when the group needs something a fragment cannot provide:
- A fragment cannot take a
className,style, or event handler. If the group needs styling or a click handler, use an element. - A fragment has no DOM node. You cannot attach a ref to it or measure it, and libraries that need a single DOM root for a component, such as some animation tools, may need an element.
- If the group has semantic meaning, such as a card, a section, or a form field with its label, use the matching element.
Do not use fragments to avoid thinking about structure. A single child inside a fragment, as in <><p>Hi</p></>, adds nothing and should be written as <p>Hi</p>.
State and identity
React decides whether to keep or reset a component's state by looking at its position and type in the tree. Wrapping an element in a fragment does not change its position, because React treats the fragment as transparent for DOM output. It does, however, change the shape of the element tree, which matters in one case: switching between returning an element and returning a fragment at the same place. Because the types differ, React treats them as different and resets state in the subtree. Keep the returned shape stable when you want state to persist.
Checking your work
When a fragment seems not to work, open the browser's element inspector. The elements you grouped should appear as direct children of the nearest real ancestor. If an extra element appears, search your component for a leftover wrapper. If a list warns about keys, check which element sits at the top level of the map callback, and confirm that it carries the key.
Exercise
A component renders a table row for each item in items, and each item needs two rows: a summary tr and a details tr. Write the tbody contents so that each item returns both rows, using a stable key from item.id. Why can you not use <>...</> here, and why not a div?
Show answer
Use the long form with a key: <tbody>{items.map((item) => (<Fragment key={item.id}><tr><td>{item.summary}</td></tr><tr><td>{item.details}</td></tr></Fragment>))}</tbody>, with import { Fragment } from 'react'. The short form <> cannot take a key, so React would warn about missing keys. A div is invalid inside tbody, because only tr rows are allowed, and the browser may move it out of the table.
Exercise
A component returns <><p>Hi</p></> in one branch and <p>Hi</p> in another, depending on a prop. A form input inside that p loses its typed text when the prop changes. What is the likely cause, and how do you fix it?
Show answer
React sees a different element type at that position (Fragment in one branch, p in the other), so it discards the subtree and its state. Return the same shape in both branches. In this case, drop the pointless fragment and return <p>Hi</p> in both.