I want to be able to check all tree node when i check the Check all checkbox, this is an example below :

This is my code, have you any idea which state should I change please ? Thank you!
CodePudding user response:
Just remove <Checkbox onChange={onChange}>Select All</Checkbox> and add one parent level to treeData with children. Example:
const treeData = [
{
title: 'Select all',
key: 'all',
children: [
{
title: '0-0',
key: '0-0',
children: [
{
title: '0-0-0',
key: '0-0-0',
children: [
{
title: '0-0-0-0',
key: '0-0-0-0',
},
{
title: '0-0-0-1',
key: '0-0-0-1',
},
{
title: '0-0-0-2',
key: '0-0-0-2',
},
],
},
{
title: '0-0-1',
key: '0-0-1',
children: [
{
title: '0-0-1-0',
key: '0-0-1-0',
},
{
title: '0-0-1-1',
key: '0-0-1-1',
},
{
title: '0-0-1-2',
key: '0-0-1-2',
},
],
},
{
title: '0-0-2',
key: '0-0-2',
},
],
},
{
title: '0-1',
key: '0-1',
children: [
{
title: '0-1-0-0',
key: '0-1-0-0',
},
{
title: '0-1-0-1',
key: '0-1-0-1',
},
{
title: '0-1-0-2',
key: '0-1-0-2',
},
],
},
{
title: '0-2',
key: '0-2',
},
],
},
];
CodePudding user response:
Well, you are using tree in controlled mode which means you must pass keys of all tree nodes to the setCheckedKeys if you want to achieve what you want.
For that you can use this function to know all the keys of your tree:
// Call this once
let getAllKeys = (tree) => {
let result = [];
tree.forEach((x) => {
let childKeys = [];
if (x.children) {
childKeys = getAllKeys(x.children);
}
result.push(...[x.key, ...childKeys]);
});
return result;
};
let allKeys = getAllKeys(treeData);
Then just:
const onChange = () => {
setCheckedKeys(allKeys);
};
