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:
<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>.Rules:
indeterminate DOM property to true (and checked to false) for this state. React has no prop for it, so you will need a ref.Given Fruits → (Apple, Banana, Citrus → (Lemon, Orange)):
<NestedCheckboxes
data={[
{
id: "fruits",
label: "Fruits",
children: [
{ id: "apple", label: "Apple" },
{ id: "banana", label: "Banana" },
],
},
{ id: "bread", label: "Bread" },
]}
/>