From e5812758c6e8e5082fd2b6226305a889dfe0b8c0 Mon Sep 17 00:00:00 2001 From: emyarod Date: Tue, 8 Sep 2020 10:47:56 -0500 Subject: [PATCH 1/2] fix(TreeNode): sync expanded prop and state --- packages/react/src/components/TreeView/TreeNode.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/react/src/components/TreeView/TreeNode.js b/packages/react/src/components/TreeView/TreeNode.js index bd5d82aec208..4505f60477de 100644 --- a/packages/react/src/components/TreeView/TreeNode.js +++ b/packages/react/src/components/TreeView/TreeNode.js @@ -166,8 +166,8 @@ export default function TreeNode({ } // sync props and state - setExpanded(expanded); - }, [children, depth, expanded, Icon]); + setExpanded(isExpanded); + }, [children, depth, Icon, isExpanded]); const treeNodeProps = { ...rest, From 9d99b08754e0434621289bbb5093f71740c8088a Mon Sep 17 00:00:00 2001 From: emyarod Date: Tue, 8 Sep 2020 10:48:17 -0500 Subject: [PATCH 2/2] docs(TreeView): add controlled expansion example --- .../src/components/TreeView/TreeView-story.js | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/packages/react/src/components/TreeView/TreeView-story.js b/packages/react/src/components/TreeView/TreeView-story.js index 306ff9d2f21a..0cdceff624c0 100644 --- a/packages/react/src/components/TreeView/TreeView-story.js +++ b/packages/react/src/components/TreeView/TreeView-story.js @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -import React from 'react'; +import React, { useState } from 'react'; import { Document16, Folder16 } from '@carbon/icons-react'; import { action } from '@storybook/addon-actions'; import { @@ -233,16 +233,17 @@ const nodes = [ }, ]; -function renderTree({ nodes, withIcons = false }) { +function renderTree({ nodes, expanded, withIcons = false }) { if (!nodes) { return; } - return nodes.map(({ children, renderIcon, ...nodeProps }) => ( + return nodes.map(({ children, renderIcon, isExpanded, ...nodeProps }) => ( - {renderTree({ nodes: children, withIcons })} + {renderTree({ nodes: children, expanded, withIcons })} )); } @@ -283,3 +284,25 @@ export const WithIcons = () => ( ); WithIcons.storyName = 'with icons'; + +export const WithControlledExpansion = () => { + const [expanded, setExpanded] = useState(undefined); + return ( + <> + +
+ + +
+ {renderTree({ nodes, expanded })} + + ); +};