84Build a tree view with expand, collapse, and checkbox selection
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 undernode(or[node.id]for a leaf).checkState(node, checked):"checked","unchecked"or"indeterminate"for aSetof checked leaf ids.toggleNode(node, checked): a newSet. 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}>whosecheckedandindeterminateproperties followcheckState; - parents have a
<button aria-label="Expand {label}" aria-expanded>(its label switches toCollapse {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.
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.