- ` — you need `React.Fragment` with a `key` prop (the short `<>` syntax does not accept props). This is a specific use-case but an important one to know.
Deeply nested data can create deeply nested `map()` calls that are hard to read. The solution is to extract the inner rendering logic into its own component. A `
React
Beginner
1 min read
Nested Lists and Keyed Fragments
Example
import React from 'react';
const catalog = [
{
id: 'cat-1',
name: 'Frontend',
products: [
{ id: 'p-1', name: 'React Course', price: 49 },
{ id: 'p-2', name: 'CSS Mastery', price: 29 },
],
},
{
id: 'cat-2',
name: 'Backend',
products: [
{ id: 'p-3', name: 'Node.js API', price: 59 },
{ id: 'p-4', name: 'SQL Deep Dive', price: 39 },
],
},
];
// Inner component for each category's product list
function ProductList({ products }) {
return (
<ul style={{ marginTop: 4 }}>
{products.map(p => (
<li key={p.id} style={{ padding: '2px 0' }}>
{p.name} — <strong>${p.price}</strong>
</li>
))}
</ul>
);
}
// Outer component renders the category list
function Catalog() {
return (
<div>
{catalog.map(cat => (
<section key={cat.id} style={{ marginBottom: 20 }}>
<h3>{cat.name}</h3>
<ProductList products={cat.products} />
</section>
))}
</div>
);
}
// Keyed Fragment example — for <dl> term/definition pairs
function GlossaryList({ terms }) {
return (
<dl>
{terms.map(({ id, term, definition }) => (
<React.Fragment key={id}>
<dt><strong>{term}</strong></dt>
<dd>{definition}</dd>
</React.Fragment>
))}
</dl>
);
}
export default Catalog;