Skip to content

Instantly share code, notes, and snippets.

@lixiaoyan
Last active December 12, 2017 16:52
Show Gist options
  • Save lixiaoyan/daa71d4342e7a9b7ce45a7ff75339110 to your computer and use it in GitHub Desktop.
Save lixiaoyan/daa71d4342e7a9b7ce45a7ff75339110 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