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.
| Group | Rendering & State |
|---|---|
| Kind | Pattern |
| Since | Earliest 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 Rendering & State
💡 Related Cases
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.