Last active
November 10, 2016 21:02
-
-
Save moodysalem/59fedd78f99fcc4e8c22cd9b764265ed to your computer and use it in GitHub Desktop.
Render children to a div tag at the end of the body
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, { Children, PureComponent, PropTypes } from 'react'; | |
import { unmountComponentAtNode, unstable_renderSubtreeIntoContainer } from 'react-dom'; | |
// renders children at the end of the body | |
export default class Portal extends PureComponent { | |
static propTypes = { | |
children: PropTypes.node.isRequired | |
}; | |
componentDidMount() { | |
this._el = document.createElement('div'); | |
document.body.appendChild(this._el); | |
this.renderIntoEl(); | |
} | |
renderIntoEl = () => { | |
const { children } = this.props; | |
unstable_renderSubtreeIntoContainer( | |
this, | |
Children.only(children), | |
this._el | |
); | |
}; | |
componentDidUpdate({ children }) { | |
if (children !== this.props.children) { | |
this.renderIntoEl(); | |
} | |
} | |
componentWillUnmount() { | |
unmountComponentAtNode(this._el); | |
document.body.removeChild(this._el); | |
} | |
render() { | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment