Last active
September 14, 2017 16:15
-
-
Save apostolos/4b46a51ac7c97bc06dd9840cd08bbc1b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import ReactDOM from 'react-dom'; | |
/** | |
* This component detaches its contents and re-attaches them to document.body (using ReactDOM.createPortal). | |
* Use it when you need to circumvent DOM z-stacking (for dialogs, popovers, etc.). | |
*/ | |
class Portal extends React.Component { | |
targetElement = null; | |
render() { | |
if (this.targetElement === null) { | |
this.targetElement = document.body.appendChild(document.createElement('div')); | |
} | |
const { children, ...rest } = this.props; | |
return ReactDOM.createPortal( | |
<div {...rest}> | |
{children} | |
</div>, | |
this.targetElement | |
); | |
} | |
componentWillUnmount() { | |
if (this.targetElement !== null) { | |
document.body.removeChild(this.targetElement); | |
this.targetElement = null; | |
} | |
} | |
} | |
export default Portal; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment