-
-
Save chebotiuk/12976b0453b594af67d6ed0967a9e37f to your computer and use it in GitHub Desktop.
React 16: Portal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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