FrontendPro

84Build a tree view with expand, collapse, and checkbox selection

mediumAbout 40 minutesCodingreacttreesrecursioncheckboxes

Problem

Build a tree of checkboxes like a file-permission or category picker. Nodes are { id, label, children? }; nodes without children are leaves.

Selection is stored as the set of checked leaf ids. A parent is:

  • checked when all its leaves are checked,
  • unchecked when none are,
  • indeterminate otherwise.

First write helpers:

  • leafIds(node): every leaf id under node (or [node.id] for a leaf).
  • checkState(node, checked): "checked", "unchecked" or "indeterminate" for a Set of checked leaf ids.
  • toggleNode(node, checked): a new Set. If the node is fully checked, uncheck all its leaves; otherwise check all of them.

Then build <CheckboxTree nodes={roots} defaultChecked={[]} defaultExpanded={[]} onChange={fn} />:

  • each node has <input type="checkbox" aria-label={label}> whose checked and indeterminate properties follow checkState;
  • parents have a <button aria-label="Expand {label}" aria-expanded> (its label switches to Collapse {label}); children render only when expanded;
  • call onChange(sortedLeafIds) after every toggle.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Step-by-step

If you stored parent states too, every toggle would need to update ancestors and descendants and keep them consistent. Storing only checked leaves makes parent states derived, so they can never be wrong.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever