SyntaxStudy
Sign Up
React Nested Lists and Keyed Fragments
React Beginner 1 min read

Nested Lists and Keyed Fragments

Nested lists arise naturally in any hierarchical data — a tree of categories and products, a multi-level navigation menu, or a grouped timeline. Rendering them in React follows the same pattern as flat lists: outer `map()` for the top-level items, inner `map()` for each item's children. Each level must assign its own `key` prop, and the keys only need to be unique within their sibling set — a product key of `1` inside category `A` is independent of product key `1` inside category `B`. When you need a list whose top-level items are themselves rendered as pairs of elements — such as `
` and `
` inside a `
` — 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 `` component handles the inner list while the outer `map()` stays clean. This decomposition also makes individual parts of the tree independently testable and reusable. Virtualization libraries like `react-window` or `@tanstack/virtual` are essential when the total number of DOM nodes is large (thousands of items), but for typical lists with fewer than a few hundred items plain `map()` is performant enough.
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;