Sub topic 7
Keys on Fragments
This chapter assumes you can render a list with map, you know why list items need a key, and you have used function components, props, and useState. Here you will learn what to do when each list item must produce more than one sibling element, and why the short Fragment syntax cannot carry a key.
The problem: one item, two elements
A component, or the callback you pass to map, must return a single root. Often a list item naturally produces two or more sibling elements. A description list (<dl>) is the classic case. Each entry is a <dt> (term) followed by a <dd> (definition). Both must be direct children of the <dl>.
You cannot wrap them in a <div>. HTML does not allow it in most contexts, and in tables it breaks the layout. You also cannot return two elements side by side from a callback:
// Syntax error: adjacent JSX elements must be wrapped
entries.map(entry => (
<dt>{entry.term}</dt>
<dd>{entry.definition}</dd>
))A Fragment solves this. A Fragment groups elements without adding a node to the DOM (the browser's tree of page elements).
The short syntax cannot take a key
You probably know the short Fragment syntax, <>...</>. It is convenient, but it is syntax sugar with no place for attributes. So this does not work:
// Not valid: the short syntax accepts no attributes
<key={entry.id}>
<dt>{entry.term}</dt>
<dd>{entry.definition}</dd>
</>If you use <>...</> inside map, the code is valid, but React cannot see a key on the outermost element returned for each item. React then warns in the console that each child in a list should have a unique key prop.
The fix is to import Fragment from React and use its long form, which accepts key.
import { Fragment } from 'react';
function Glossary({ entries }) {
return (
<dl>
{entries.map(entry => (
<Fragment key={entry.id}>
<dt>{entry.term}</dt>
<dd>{entry.definition}</dd>
</Fragment>
))}
</dl>
);
}Three details matter here:
- The
keygoes on the outermost element thatmapreturns, which is theFragment. Putting keys on the inner<dt>and<dd>would not help, because React compares the items in the array, and each item is the Fragment. keyis the only prop a Fragment accepts besideschildren. In current React versions, passing any other prop to a Fragment produces a warning.- The
Fragmentimport is a named import. WritingReact.Fragmentalso works if you already importReact.
What React does with the key
React uses the key to match each item in the new render to the same item in the previous render. When the list changes, React uses keys to decide which items were added, removed, or moved.
For a keyed Fragment, the key identifies the whole group. If the entry with id 7 moves from third to first position, React moves both the <dt> and the <dd> in the DOM, instead of rewriting their text. Any state in components inside that group stays with the entry.
// Before: ids 5, 6, 7
// After: ids 7, 5, 6
// React moves the 7 group to the front. It does not rebuild all three.The key rules from earlier chapters still apply:
- The key must be unique among siblings, not globally.
- The key should be stable. Use an id from your data, not the array index, if the list can be reordered, filtered, or edited.
- Do not generate keys during render with
Math.random()orcrypto.randomUUID(). A new key each render makes React destroy and recreate every item.
Where the key goes when items are components
Suppose you extract the item into its own component:
import { Fragment } from 'react';
function GlossaryEntry({ entry }) {
return (
<>
<dt>{entry.term}</dt>
<dd>{entry.definition}</dd>
</>
);
}
function Glossary({ entries }) {
return (
<dl>
{entries.map(entry => (
<GlossaryEntry key={entry.id} entry={entry} />
))}
</dl>
);
}Here the short syntax is fine inside GlossaryEntry. The key sits on the <GlossaryEntry> element in the map call, and that element is what the array contains. The short Fragment is only an internal detail of the component.
Choose between the two approaches like this:
| Situation | Approach |
|---|---|
| The markup is small and used only in this list | `Fragment` with a key, inline in `map` |
| The item has its own logic, state, or is reused elsewhere | Extract a component, key it in `map`, use `<>` inside |
Notice that the key never goes inside the extracted component, on its root element. A key set there is invisible to the list, because the list holds the <GlossaryEntry> elements.
Tables and other strict parents
Fragments with keys matter most where HTML restricts what a parent may contain. A table body accepts only rows, and a row accepts only cells. A common case is a data row followed by a detail row:
import { Fragment, useState } from 'react';
function OrdersTable({ orders }) {
const [openId, setOpenId] = useState(null);
return (
<table>
<tbody>
{orders.map(order => (
<Fragment key={order.id}>
<tr>
<td>{order.customer}</td>
<td>
<button onClick={() => setOpenId(openId === order.id ? null : order.id)}>
{openId === order.id ? 'Hide' : 'Show'} details
</button>
</td>
</tr>
{openId === order.id && (
<tr>
<td colSpan={2}>{order.notes}</td>
</tr>
)}
</Fragment>
))}
</tbody>
</table>
);
}A wrapping <div> around the two <tr> elements would produce invalid table markup and can break browser rendering. The keyed Fragment adds nothing to the DOM, so the rows stay direct children of <tbody>.
This example also uses && with a boolean comparison on the left side. The comparison openId === order.id yields true or false, so the 0 pitfall from the && chapter cannot occur.
Common errors
Using `<>` inside `map` and expecting no warning
This is the most common mistake. The code renders correctly, but React logs a key warning. Switch to <Fragment key={...}>.
Putting the key on a child instead of the Fragment
// Wrong: keys on the children, none on the Fragment
{entries.map(entry => (
<Fragment>
<dt key={entry.id}>{entry.term}</dt>
<dd key={entry.id}>{entry.definition}</dd>
</Fragment>
))}The warning remains, because the array items are the Fragments. Move the key to the Fragment and remove it from the children.
Reusing the same key for the two children
If you try to fix the example above by giving both children the same key, you do not get a clean result either. Keys on the children only matter when the children themselves come from an array. Here they do not, so those keys do nothing.
Duplicate keys across entries
If two entries share an id, React warns about duplicate keys and may skip or duplicate items when the list updates. Check that your data ids are unique. If you merge lists from two sources, ids can collide. Combine them into one key, such as ` ${entry.source}-${entry.id} `.
Using the index as the key for editable lists
An index key works only when the list never reorders and items hold no state. With a keyed Fragment the same rule applies. If the user can delete the first entry, every index shifts, and React reuses the wrong DOM nodes and state for the remaining groups.
A note on diagrams of the structure
The following diagram shows how the list data maps to Fragments and then to DOM nodes. The Fragments themselves do not appear in the DOM.
Summary of rules
- Use
<Fragment key={id}>when amapcallback returns several sibling elements and you do not want a wrapper node. - The short
<>...</>syntax cannot take a key, so it is for cases outside a list or inside an extracted component. - Put the key on the outermost element the callback returns.
- Choose ids that are unique and stable.
Exercise
A teammate writes entries.map(entry => (<><dt key={entry.id}>{entry.term}</dt><dd key={entry.id}>{entry.definition}</dd></>)) and still sees the "each child in a list should have a unique key" warning. Why does the warning persist, and how do you fix it?
Show answer
The array that map produces contains the fragments, not the dt and dd elements, so the fragments are the items that need keys. The short <></> syntax cannot take a key. Import Fragment from 'react', write <Fragment key={entry.id}>...</Fragment> around the dt and dd, and remove the keys from the dt and dd.
Exercise
You extract the Glossary item into a GlossaryEntry component that returns <>...</>. Where do you place the key, and why does the short syntax work here?
Show answer
Place the key on the <GlossaryEntry key={entry.id} entry={entry} /> element inside map. That element is what the array contains, so React reads the key from it. The short Fragment is only inside the component and is never an item in the array.