diff --git a/packages/material-ui-lab/src/TreeItem/TreeItem.js b/packages/material-ui-lab/src/TreeItem/TreeItem.js
index 3146ee0c6bc955..6b29a4c902ea57 100644
--- a/packages/material-ui-lab/src/TreeItem/TreeItem.js
+++ b/packages/material-ui-lab/src/TreeItem/TreeItem.js
@@ -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]);
diff --git a/packages/material-ui-lab/src/TreeItem/TreeItem.test.js b/packages/material-ui-lab/src/TreeItem/TreeItem.test.js
index b1e9b616bba70d..f6a7fa7250f914 100644
--- a/packages/material-ui-lab/src/TreeItem/TreeItem.test.js
+++ b/packages/material-ui-lab/src/TreeItem/TreeItem.test.js
@@ -77,6 +77,32 @@ describe('', () => {
expect(getIcon('6')).attribute('data-test').to.equal('endIcon');
});
+ it('should allow conditional child', () => {
+ function TestComponent() {
+ const [hide, setState] = React.useState(false);
+
+ return (
+
+
+
+
+ {!hide && }
+
+
+
+ );
+ }
+ const { getByTestId, queryByTestId } = render();
+
+ 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(