Skip to content

Instantly share code, notes, and snippets.

@moodysalem
Last active November 10, 2016 21:02
Show Gist options
  • Save moodysalem/59fedd78f99fcc4e8c22cd9b764265ed to your computer and use it in GitHub Desktop.
Save moodysalem/59fedd78f99fcc4e8c22cd9b764265ed to your computer and use it in GitHub Desktop.
Render children to a div tag at the end of the body
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