Skip to content

Instantly share code, notes, and snippets.

@zry656565
Last active October 6, 2017 08:02
Show Gist options
  • Save zry656565/0fc2bcffe7bb319e6412bd16ca5c1ae6 to your computer and use it in GitHub Desktop.
Save zry656565/0fc2bcffe7bb319e6412bd16ca5c1ae6 to your computer and use it in GitHub Desktop.
Portal Pattern
// 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