Back

Tree Navigation I

easy

Streak

0 days

Progress

0%

Submitted

0

Tree Navigation I

React30 mineasyFreeNew

Prompt

Tree Navigation I introduces rendering a simple file-system-like tree with expand/collapse. Each node can be a folder (has children, toggleable) or a file (leaf, clickable to select). This is the foundation for all recursive tree UI components.

Build a component that takes a nested tree data structure and renders it as an indented, collapsible list. Folders show a chevron icon that rotates on expand. Files show a file icon and highlight when selected. Clicking a folder toggles its children; clicking a file selects it.

This question tests recursive React components, local state for collapse/expand, and selection state management. The key is keeping the data structure pure and storing UI state (open/selected) separately.

Requirements

  • →Render arbitrarily deep nested tree
  • →Folders are toggleable (expand/collapse)
  • →Files are selectable (highlight on click)
  • →Indentation increases with depth
  • →Folder icon rotates on expand
  • →Selected file persists until another is clicked
Example
Loading preview...
For the best coding experience, we recommend using a desktop device.
Preparing Sandbox...
Premium interview report

What interviewers score in this build

Use this before reading the code. It tells you what to say, what to test, and where machine-coding candidates usually lose points.

Interview signals

  • Recursive rendering: TreeNode calls itself for each child node
  • Centralised UI state: Open Set and selected ID in root parent, not child components
  • Immutable Set toggle: new Set(prev) on each toggle
  • Depth-based indentation: depth * 16px left margin

Time checkpoints

  1. 1

    0–3 min: Explain recursive approach and centralised state

  2. 2

    3–8 min: Build TreeNode rendering leaf and folder cases

  3. 3

    8–13 min: Add recursion with depth-based indentation

  4. 4

    13–17 min: Implement open Set toggle with immutable update

Edge-case checklist

Empty data and first-load state
Slow network, failed request, and retry path
Keyboard navigation and focus movement
Large input size, re-render pressure, and cleanup

Common mistakes

  • Starting with JSX before naming state and events.
  • Ignoring accessibility until the final minute.
  • Over-building abstractions instead of finishing the required behavior.
  • Failing to narrate trade-offs while coding.
SolutionRead-only · Live Preview

Technical Explanation

Why This Question Exists

Tree Navigation I is a pure recursive component challenge — the simplest possible version. The interviewer is evaluating whether you naturally model recursive data with recursive components, and whether you centralise UI state at the correct level. Candidates who put open/selected state inside each TreeNode fail the "expand all" button test — you can't control per-node state from outside if it's internal to each node.

Recursive Component Pattern

function TreeNode({ node, depth = 0, open, toggle, selected, select }) {
  const isFolder = Array.isArray(node.children);

  if (!isFolder) {
    // Base case: leaf node — render a selectable file
    return (
      <div style={{ marginLeft: depth * 16 }} onClick={() => select(node.id)}>
        📄 {node.name}
      </div>
    );
  }

  // Recursive case: render folder + its children
  const isOpen = open.has(node.id);
  return (
    <div>
      <div style={{ marginLeft: depth * 16 }} onClick={() => toggle(node.id)}>
        {isOpen ? '📂' : '📁'} {node.name}
      </div>
      {isOpen && node.children.map(child => (
        <TreeNode key={child.id} node={child} depth={depth + 1}
          open={open} toggle={toggle} selected={selected} select={select} />
      ))}
    </div>
  );
}
ℹ Interview Tip

Say: "I keep the open Set and selected ID in the root parent component. This makes the tree fully controlled — any external code can programmatically expand, collapse, or select nodes by updating those values. If I put the state inside each TreeNode, I'd lose that control."

Centralised State Design

// In the root App component — NOT inside TreeNode
const [open, setOpen]       = useState(new Set(['root'])); // root expanded by default
const [selected, setSelected] = useState(null);

const toggle = (id) => setOpen(prev => {
  const next = new Set(prev);
  next.has(id) ? next.delete(id) : next.add(id);
  return next; // new Set — React detects the change
});

// Pass all state down as props — TreeNode has zero internal state

With centralised state, an "Expand All" button is just setOpen(new Set(allFolderIds)). A "Collapse All" button is setOpen(new Set()). These are trivial to implement because state lives at the top.

Folder vs File Detection

// Option 1: type field in data
const isFolder = node.type === 'folder';

// Option 2: presence of children array (used here)
const isFolder = Array.isArray(node.children);
// children: [] → empty folder (still a folder!)
// children: undefined → file

Using the presence of a children array is the most common approach. An empty array is a valid empty folder (a folder that happens to have no files yet). Undefined/null means it's a file.

⚠ Common Pitfall: Infinite recursion with circular data

If the tree data has circular references (e.g., a child references its own parent), a recursive component will infinite-loop. Always validate tree data before rendering. In interviews, it's enough to mention this and say you'd validate the input data structure at the API layer.

Interview Criteria

Recursive rendering

TreeNode calls itself for each child node

Centralised UI state

Open Set and selected ID in root parent, not child components

Immutable Set toggle

new Set(prev) on each toggle

Depth-based indentation

depth * 16px left margin

Folder vs file distinction

Children presence determines folder vs file behaviour

Time Checkpoints

0–3 min

0–3 min: Explain recursive approach and centralised state

3–8 min

3–8 min: Build TreeNode rendering leaf and folder cases

8–13 min

8–13 min: Add recursion with depth-based indentation

13–17 min

13–17 min: Implement open Set toggle with immutable update

17–21 min

17–21 min: Add selection state and highlight styling

21–25 min

21–25 min: Test deep nesting and multiple simultaneous open folders

Streak

0 days

Last active: Sign in to track

Progress

0%

0/0 solved

Submitted

0

Solutions pushed to review history.