From 1fecba92307041e181ce425082d4d21ec8928728 Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Mon, 11 Feb 2019 18:37:53 +0000 Subject: [PATCH] Fix crash unmounting an empty Portal (#14820) * Adds failing test for https://github.com/facebook/react/issues/14811 * Fix removeChild() crash when removing an empty Portal --- .../src/__tests__/ReactDOMFiber-test.js | 34 +++++++++++++++++++ .../src/ReactFiberCommitWork.js | 10 +++--- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/packages/react-dom/src/__tests__/ReactDOMFiber-test.js b/packages/react-dom/src/__tests__/ReactDOMFiber-test.js index 864caa0f33..c19777e7e5 100644 --- a/packages/react-dom/src/__tests__/ReactDOMFiber-test.js +++ b/packages/react-dom/src/__tests__/ReactDOMFiber-test.js @@ -461,6 +461,40 @@ describe('ReactDOMFiber', () => { expect(container.innerHTML).toBe('
'); }); + it('should unmount empty portal component wherever it appears', () => { + const portalContainer = document.createElement('div'); + + class Wrapper extends React.Component { + constructor(props) { + super(props); + this.state = { + show: true, + }; + } + render() { + return ( +
+ {this.state.show && ( + + {ReactDOM.createPortal(null, portalContainer)} +
child
+
+ )} +
parent
+
+ ); + } + } + + const instance = ReactDOM.render(, container); + expect(container.innerHTML).toBe( + '
child
parent
', + ); + instance.setState({show: false}); + expect(instance.state.show).toBe(false); + expect(container.innerHTML).toBe('
parent
'); + }); + it('should keep track of namespace across portals (simple)', () => { assertNamespacesMatch( diff --git a/packages/react-reconciler/src/ReactFiberCommitWork.js b/packages/react-reconciler/src/ReactFiberCommitWork.js index 85231dd068..06ad89eaf1 100644 --- a/packages/react-reconciler/src/ReactFiberCommitWork.js +++ b/packages/react-reconciler/src/ReactFiberCommitWork.js @@ -1038,12 +1038,12 @@ function unmountHostComponents(current): void { } // Don't visit children because we already visited them. } else if (node.tag === HostPortal) { - // When we go into a portal, it becomes the parent to remove from. - // We will reassign it back when we pop the portal on the way up. - currentParent = node.stateNode.containerInfo; - currentParentIsContainer = true; - // Visit children because portals might contain host components. if (node.child !== null) { + // When we go into a portal, it becomes the parent to remove from. + // We will reassign it back when we pop the portal on the way up. + currentParent = node.stateNode.containerInfo; + currentParentIsContainer = true; + // Visit children because portals might contain host components. node.child.return = node; node = node.child; continue;