Created
June 4, 2019 22:31
-
-
Save brandoncc/e5595667be221d3f48b03b64652b8958 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 React from 'react'; | |
import ReactDOM from 'react-dom'; | |
export default class Portal extends React.Component { | |
root = null; | |
constructor(props) { | |
super(props); | |
this.el = document.createElement('div'); | |
} | |
componentDidMount() { | |
this.root = document.getElementById('portal-root'); | |
// The portal element is inserted in the DOM tree after | |
// the Modal's children are mounted, meaning that children | |
// will be mounted on a detached DOM node. If a child | |
// component requires to be attached to the DOM tree | |
// immediately when mounted, for example to measure a | |
// DOM node, or uses 'autoFocus' in a descendant, add | |
// state to Modal and only render the children when Modal | |
// is inserted in the DOM tree. | |
this.root && this.root.appendChild(this.el); | |
} | |
componentWillUnmount() { | |
this.root && this.root.removeChild(this.el); | |
} | |
render() { | |
return ReactDOM.createPortal( | |
this.props.children, | |
this.el, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment