Skip to content

Instantly share code, notes, and snippets.

@chebotiuk
Forked from bisubus/Portal.js
Created December 14, 2017 14:24
Show Gist options
  • Save chebotiuk/12976b0453b594af67d6ed0967a9e37f to your computer and use it in GitHub Desktop.
Save chebotiuk/12976b0453b594af67d6ed0967a9e37f to your computer and use it in GitHub Desktop.
React 16: Portal
import React from "react";
import PropTypes from "prop-types";
import { createPortal } from "react-dom";
class Portal extends React.Component {
static propTypes = {
children: PropTypes.node,
};
state = { mounted: false };
target = null;
componentDidMount() {
this.setState({ mounted: true });
}
componentWillUnmount() {
if (this.target) {
this.target.remove();
}
}
getTarget() {
if (!this.target) {
this.target = document.createElement("div");
document.body.appendChild(this.target);
}
return this.target;
}
render() {
if (!this.state.mounted) {
return null;
}
return createPortal(this.props.children, this.getTarget());
}
}
export default Portal;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment