Skip to content

Commit

Permalink
fix(TreeNode): sync expanded prop and state (#6791)
Browse files Browse the repository at this point in the history
* fix(TreeNode): sync expanded prop and state

* docs(TreeView): add controlled expansion example

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
emyarod and kodiakhq[bot] authored Sep 9, 2020
1 parent 260708f commit 127b923
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
4 changes: 2 additions & 2 deletions packages/react/src/components/TreeView/TreeNode.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
31 changes: 27 additions & 4 deletions packages/react/src/components/TreeView/TreeView-story.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 }) => (
<TreeNode
key={nodeProps.id}
renderIcon={withIcons ? renderIcon : null}
isExpanded={expanded ?? isExpanded}
{...nodeProps}>
{renderTree({ nodes: children, withIcons })}
{renderTree({ nodes: children, expanded, withIcons })}
</TreeNode>
));
}
Expand Down Expand Up @@ -283,3 +284,25 @@ export const WithIcons = () => (
);

WithIcons.storyName = 'with icons';

export const WithControlledExpansion = () => {
const [expanded, setExpanded] = useState(undefined);
return (
<>
<InlineNotification
kind="info"
title="Experimental component"
subtitle="An accessibility review of this component is in progress"
/>
<div style={{ marginBottom: '1rem' }}>
<button type="button" onClick={() => setExpanded(true)}>
expand all
</button>
<button type="button" onClick={() => setExpanded(false)}>
collapse all
</button>
</div>
<TreeView {...props()}>{renderTree({ nodes, expanded })}</TreeView>
</>
);
};

0 comments on commit 127b923

Please sign in to comment.