KatInterview

Collapsible Nested Menu with ARIA Support

Trees & GraphsModel answer
MediumModel answerTrees & Graphsreactrecursionaccessibility

Last updated

Design and code a React component that displays hierarchical data with interactive expand/collapse behavior and full keyboard accessibility.

Hierarchical Menu Component

Your task is to build a Tree component in React that displays hierarchical information. Users should be able to expand and collapse branches of the tree independently.

Component Requirements

Data Format
The component receives an array of node objects. Each node contains:

  • id (string): unique identifier
  • label (string): display text
  • children (array, optional): nested nodes following the same structure

Example:

[
  {
    "id": "root-1",
    "label": "Documents",
    "children": [
      { "id": "node-2", "label": "README.md" },
      { 
        "id": "node-3", 
        "label": "src", 
        "children": [
          { "id": "node-4", "label": "index.js" }
        ] 
      }
    ]
  }
]

Functional Behavior

  • Nodes with children should display a toggle control
  • Clicking the toggle expands or collapses that node's children
  • Each node's expansion state is independent
  • Leaf nodes (no children) should not show a toggle

Accessibility Standards

  • Use appropriate ARIA roles: role="tree" for the container, role="treeitem" for each node
  • Include aria-expanded on expandable nodes to indicate current state
  • Ensure toggle controls are keyboard accessible (Space and Enter keys)
  • Use semantic HTML elements (prefer <button> for interactive controls)

Performance

  • Use stable React keys derived from node IDs to prevent unnecessary reconciliation
  • Avoid re-rendering unaffected nodes when toggling one branch

Expected Usage

<Tree data={treeData} />

Edge Cases to Handle

  • Empty array or null data
  • Nodes without children
  • Deeply nested structures (10+ levels)
  • Rapidly toggling the same node

Hints

Hint 1

Consider where expansion state should live—local component state or a shared store?

Hint 2

Recursive components naturally mirror recursive data structures.

Hint 3

useSyncExternalStore can optimize subscriptions to specific slices of state.