I am trying to implement a checkbox tree in react that can toggle checked property nodes according to the following rules
Here's the data structure that I am following:
let data = [
{
field: 'ARTICLE',
id: 41,
name: 'Article',
parentId: null,
checked: false,
children: [
{
field: 'red',
id: 43,
name: 'red',
parentId: 41,
checked: false,
},
{
field: 'article.colorCode',
id: 42,
name: 'Color',
parentId: 41,
checked: false,
children: [
{
children: [],
field: 'test',
id: 44,
name: 'red',
parentId: 42,
checked: false,
},
],
},
],
},
{
children: [],
field: 'red',
id: 45,
name: 'red',
parentId: 41,
checked: false,
},
];
If I check the item with id 44, then the item with id 42 should get checked as well. I am doing this programmatically as I need the list of checked items in the defined hierarchy and I having a hard time with recursion.
Could someone please help me with a solution for the second point mentioned above?
For the first point, this code works good
let setCheckedValueForNodeAndChildren = (item, value) => {
if (item.children) {
return {
...item,
checked: value,
children: item.children.map((x) =>
setCheckedValueForNodeAndChildren(x, value)
),
};
} else {
return { ...item, checked: value };
}
};
let toggleNodeInsideTree = (id, tree) => {
return tree.map((x) => {
if (x.id === id) {
return setCheckedValueForNodeAndChildren(x, !x.checked);
}
if (x.children) {
return { ...x, children: toggleNodeInsideTree(id, x.children) };
}
return x;
});
};
console.log(toggleNodeInsideTree(42, data));