react-checkbox-tree icon indicating copy to clipboard operation
react-checkbox-tree copied to clipboard

Dynamically added children

Open mathgameapi opened this issue 6 years ago • 4 comments

When i add the children。 if children is empty, treeview will not show the new children. if children has one or more children , it got Cannot read property 'isParent' of undefined

mathgameapi avatar Apr 17 '19 05:04 mathgameapi

Hello @mathgameapi can you post a link to a live example that shows this issue (such as on JsFiddle or CodePen)? You can modify the following working example:

https://codesandbox.io/s/1z9yny5473

jakezatecky avatar Apr 23 '19 01:04 jakezatecky

Same issue for me: Scenario 1: https://codesandbox.io/s/reactcheckboxtree-example-c557o Scenario 2: https://codesandbox.io/s/reactcheckboxtree-example-3n9yf

stephdep1973 avatar May 24 '19 01:05 stephdep1973

Thanks so much for the examples @stephdep1973! I was able to confirm the behavior you are experiencing.

The main reason this occurs is because CheckboxTree checks to see whether the new nodes property for the CheckboxTree is different than the old nodes property before performing the costly task of flattening a recursive set of nodes for performance optimizations. This optimization check is particularly relevant for trees that have thousands of individuals nodes.

With your examples, there are two main issues:

  1. You are mutating nodes but are not changing the internal state of your Widget component, so React itself does not know it needs to re-render Widget.
  2. Even if you were to update Widget's state such that React would trigger a re-render, the CheckboxTree would not pick up this change because nodes has been mutated in such a way that when CheckboxTree compares the old nodes and new nodes, if finds that they are the same, because JavaScript passes variables by reference. In other words, mutating the original nodes variable causes this issue. To avoid that, you would have to clone the original nodes, mutate the clone, and then pass it to the CheckboxTree.

See the modified Scenario 1 example below which will render the changes:

https://codesandbox.io/s/reactcheckboxtree-add-new-child-fs3he

Version 2.0 of this component may mitigate the second issue, because it might do away with the entire tree flattening operation and thus always render whatever nodes is, even if it has been directly mutated.

jakezatecky avatar May 24 '19 04:05 jakezatecky

Thank you !

Yes I also tested changing the state of the component to "force" a rendering but it did not help in both cases.

Anyway, cloning the nodes prop works fine. Thanks again !

stephdep1973 avatar May 24 '19 16:05 stephdep1973