Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(TreeNode): sync expanded prop and state #6791

Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>
</>
);
};