Skip to content

Instantly share code, notes, and snippets.

@apostolos
Last active September 14, 2017 16:15
Show Gist options
  • Save apostolos/4b46a51ac7c97bc06dd9840cd08bbc1b to your computer and use it in GitHub Desktop.
Save apostolos/4b46a51ac7c97bc06dd9840cd08bbc1b to your computer and use it in GitHub Desktop.
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