Hello I am implementing a one level TreeView with React.
One of the requirements is to un-select the parent if any of the childs is un-selected. I am starting with React and I am not sure how to do this.
Please see my whole implementation here: https://playcode.io/2019412
In TreeContext.jsx the following function:
const toggleNode = (nodes, id, parent, expanded, checked) => {
return nodes.map((node) => {
// if parent is clicked
if (node.id === id && node.children?.length > 0) {
// Check or Un-checked all children
const children = node.children;
const newChildren = children.map((child) => {
return { ...child, isChecked: checked };
});
return {
...node,
isExpanded: expanded,
isChecked: checked,
children: newChildren,
};
}
// if child is clicked
if (node.id === id && node.children === null) {
// Check individual node
return { ...node, isExpanded: expanded, isChecked: checked };
}
if (node.id === parent.toString()) {
const allChildrenChecked = node.children.every(
(child) => child.isChecked
);
}
if (node.children?.length > 0) {
return {
...node,
children: toggleNode(node.children, id, parent, expanded, checked),
};
}
return node;
});
};
Does:
- Click on parent, select/un-select and expand/collapse all children.
- Click on child select/un-select child
However, how can I implement:
- Un-select parent checkbox if any of the children are Un-selected?
- Is there are an easier way to represent the object in data.js?