Last active
October 6, 2017 08:02
-
-
Save zry656565/0fc2bcffe7bb319e6412bd16ca5c1ae6 to your computer and use it in GitHub Desktop.
Portal Pattern
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
// From: https://github.com/react-component/util | |
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
import { createPortal } from 'react-dom'; | |
export default class Portal extends React.Component { | |
static propTypes = { | |
getContainer: PropTypes.func.isRequired, | |
children: PropTypes.node.isRequired, | |
} | |
componentDidMount() { | |
this.createContainer(); | |
} | |
componentWillUnmount() { | |
this.removeContainer(); | |
} | |
createContainer() { | |
this._container = this.props.getContainer(); | |
this.forceUpdate(); | |
} | |
removeContainer() { | |
if (this._container) { | |
this._container.parentNode.removeChild(this._container); | |
} | |
} | |
render() { | |
if (this._container) { | |
return createPortal(this.props.children, this._container); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment