Skip to content

Instantly share code, notes, and snippets.

@bisubus
Forked from lixiaoyan/Portal.js
Created September 25, 2017 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bisubus/0ae2f4aa3868c42b8892f1b5592f0b63 to your computer and use it in GitHub Desktop.
Save bisubus/0ae2f4aa3868c42b8892f1b5592f0b63 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