react-checkbox-tree
react-checkbox-tree copied to clipboard
Pre-select all checkboxes
Hello, Great component!!
I have a question and if there is no answer then... i have a feature request. Are we able to pre-select the checkboxes on load?
This behaviour already exists for the expanded prop but it would be great to have this for the checked prop.
i.e:
<CheckboxTree
nodes={[
{ value: "1", label: "hello" },
{ value: "2", label: "world", children: [{ value: "3", label: "foo" }] },
]}
checked={["2"]}
/>
i would expect to see the checked box with label "world" to be checked on page load but it is not.
if i do this:
<CheckboxTree
nodes={[
{ value: "1", label: "hello" },
{ value: "2", label: "world", children: [{ value: "3", label: "foo" }] },
]}
checked={["3"]}
/>
Checkbox's "world" & "foo" are checked.
It seems that if a node has children then it requires one of it's direct children to be checked...
Is there a way to have the whole tree be pre-selected if the parent item is defined in the checked array prop? i.e the first scenario.
Thank you!
I think you can just loop over all your nodes, add their values to an array, and then in your render() method, pass that array in for the checked prop, no?
Yes you can do that but what if your tree has the ability to go 5000 deep? Thats a lot of iteration/recurssion for the browser.
I think in an ideal world if we pass all the first values into the checked array then all items should be checked. Maybe a new defaultChecked prop of some sort should be added in order to take this functionality from the checked prop.
Ah, yes, for such a large tree that use case makes sense.
At this time, no.
This has some relations to a long-standing issue to support different levels of check support (#13). In this case, it relates to allowing top-level checked items to represent state.
In the interim, you could make use of Refs to check a top-level node in a less-than-elegant way:
class Widget extends Component {
constructor(props) {
super(props);
this.tree = React.createRef();
}
componentDidMount() {
this.tree.current.onCheck({ value: '3', checked: true });
}
render() {
return (
<CheckboxTree ... ref={this.tree} />
);
}
}
Note that this will still iterate through children because leaf nodes are used as the basis for selection state.