#683 Nested Checkboxes

medium
react
ui-coding
state-management
nested-data

Build a NestedCheckboxes component that renders a tree of checkboxes, like the category filters in an online shop or the permission picker in an admin panel. Checking a group selects everything inside it, and each group shows at a glance whether all, some or none of its items are selected.

<NestedCheckboxes
  data={[
    {
      id: "fruits",
      label: "Fruits",
      children: [
        { id: "apple", label: "Apple" },
        { id: "banana", label: "Banana" },
      ],
    },
    { id: "bread", label: "Bread" },
  ]}
/>

Props:

  • data: an array of nodes shaped { id, label, children? }. children is an optional array of nodes of the same shape, so the tree can be any depth. id is unique across the whole tree. Defaults to []. You can assume it does not change after the first render.

Rendering:

  • Render the tree as nested lists: each node is an <li> holding a <label> with an <input type="checkbox"> and the node's label as text. A node with children also holds a <ul> of its children inside the same <li>.
  • Every checkbox starts unchecked.

Rules:

  • A node without children (a leaf) simply toggles when clicked.
  • Clicking a parent that is checked unchecks it and every node below it.
  • Clicking a parent that is unchecked or indeterminate checks it and every node below it.
  • After every change, each parent reflects its subtree:
    • checked when all of its children are checked,
    • unchecked when none of its children are checked or indeterminate,
    • indeterminate otherwise. Set the checkbox's indeterminate DOM property to true (and checked to false) for this state. React has no prop for it, so you will need a ref.
  • This applies at every level: a change deep in the tree can update its parent, grandparent and so on up to the root.

Example

Given Fruits → (Apple, Banana, Citrus → (Lemon, Orange)):

  1. Click Lemon. Lemon is checked, Citrus and Fruits become indeterminate.
  2. Click Orange. Citrus becomes checked; Fruits stays indeterminate because Apple and Banana are unchecked.
  3. Click Fruits. Since it was indeterminate, everything under Fruits becomes checked.
  4. Click Apple. Apple is unchecked and Fruits goes back to indeterminate; Citrus stays checked.