Nested Lists

Last updated: 2026-11-02

Nested Lists Nested Lists

When the data has a multi-level structure such as categories containing entries, you render a nested list with a map inside a map or with a recursive component. Every level keeps its own keys, indentation expresses the hierarchy, and the pattern shows up in menus, comment threads and file trees. A recursive component is the most flexible option, because it handles any depth.

GroupRendering & State
KindPattern
SinceEarliest React versions

ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.

📝 Syntax

function TreeNode({ node }) {
  return (
    <li>
      {node.name}
      {node.children?.map((kid) => (
        <TreeNode key={kid.id} node={kid} />  // Render the children recursively
      ))}
    </li>
  )
}

Returns:No return value — a coding convention and mental model.

▶ Example

The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.

Output:

A monospace interactive file tree: the root folder src can be clicked to collapse or expand, holding the file main.jsx and the sub-folder components, which in turn contains Button.jsx; the hierarchy is expressed through indentation.

💡 Key Points

💡 Tip Give tree data stable unique ids up front, and keep the expanded / collapsed state in one place keyed by id.
⚠️ Warning A recursive component needs a termination condition (children are empty) and a key on every level, otherwise it loops forever or warns.
ℹ️ Info When the depth is fixed (a two-level menu, for example), mapping inside a map is clearer; reach for a recursive component only when the depth varies.
More case studies coming soon.

📚 Related Tutorials

❓ FAQ

Q How does React render tree-shaped data?
A Two ways: when the depth is fixed, map inside a map; when the depth varies, write a recursive component that calls itself on its children.
Q What should I watch out for in recursive components?
A They need a termination condition to avoid infinite recursion, every level needs a unique key, and the expanded state is better kept in one place instead of scattered across the levels.
Q How do I set keys in a nested list?
A Each map level provides its own unique key, usually the id of the node at that level; uniqueness within a level is enough and levels may repeat.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏