0 day streak
javascript / intermediate
Snippet

Keyed Fragments for Multi-Element Mapping

While shorthand Fragments (<>...</>) are common, they don't support attributes. When mapping an array to multiple sibling elements, you must use the explicit 'Fragment' component to provide a 'key' without adding a wrapper div that would break HTML structures like description lists.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { Fragment } from 'react';
function Glossary({ terms }) {
return (
<dl>
{terms.map(item => (
<Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.definition}</dd>
</Fragment>
))}
</dl>
);
}
react
Breakdown
1
<Fragment key={item.id}>
Allows assigning a unique key to a group of sibling elements without an extra DOM node.
2
{terms.map(item => (...))}
Standard array mapping requiring a unique key for React's reconciliation process.