Skip to content

Commit

Permalink
[TreeView] Allow TreeItem to have conditional child (#20238)
Browse files Browse the repository at this point in the history
  • Loading branch information
tonyhallett committed Mar 29, 2020
1 parent 1edf5a7 commit 8b795b2
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
7 changes: 6 additions & 1 deletion packages/material-ui-lab/src/TreeItem/TreeItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -325,8 +325,13 @@ const TreeItem = React.forwardRef(function TreeItem(props, ref) {
};

React.useEffect(() => {
const childIds = React.Children.map(children, (child) => child.props.nodeId) || [];
if (addNodeToNodeMap) {
const childIds = [];
React.Children.forEach(children, (child) => {
if (React.isValidElement(child) && child.props.nodeId) {
childIds.push(child.props.nodeId);
}
});
addNodeToNodeMap(nodeId, childIds);
}
}, [children, nodeId, addNodeToNodeMap]);
Expand Down
26 changes: 26 additions & 0 deletions packages/material-ui-lab/src/TreeItem/TreeItem.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,32 @@ describe('<TreeItem />', () => {
expect(getIcon('6')).attribute('data-test').to.equal('endIcon');
});

it('should allow conditional child', () => {
function TestComponent() {
const [hide, setState] = React.useState(false);

return (
<React.Fragment>
<button data-testid="button" type="button" onClick={() => setState(true)}>
Hide
</button>
<TreeView defaultExpanded={['1']}>
<TreeItem nodeId="1" data-testid="1">
{!hide && <TreeItem nodeId="2" data-testid="2" />}
</TreeItem>
</TreeView>
</React.Fragment>
);
}
const { getByTestId, queryByTestId } = render(<TestComponent />);

expect(getByTestId('1')).to.have.attribute('aria-expanded', 'true');
expect(getByTestId('2')).to.not.be.null;
fireEvent.click(getByTestId('button'));
expect(getByTestId('1')).to.not.have.attribute('aria-expanded');
expect(queryByTestId('2')).to.be.null;
});

it('should treat an empty array equally to no children', () => {
const { getByTestId } = render(
<TreeView defaultExpanded={['1']}>
Expand Down

0 comments on commit 8b795b2

Please sign in to comment.