Created
July 7, 2022 21:56
-
-
Save mka142/eac405d3b9cac08a8fb8f14fa267fbb8 to your computer and use it in GitHub Desktop.
React portal class component
This file contains hidden or 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 ReactDOM from "react-dom"; | |
export default class PortalToElement extends React.Component { | |
constructor(props) { | |
super(props); | |
this.el = document.createElement("div"); | |
this.el.style.display = "contents"; | |
// The <div> is a necessary container for our | |
// content, but it should not affect our layout. | |
// Only works in some browsers, but generally | |
// doesn't matter since this is at | |
// the end anyway. Feel free to delete this line. | |
} | |
componentDidMount() { | |
this.props.element.appendChild(this.el); | |
} | |
componentWillUnmount() { | |
this.props.element.removeChild(this.el); | |
} | |
render() { | |
return ReactDOM.createPortal(this.props.children, this.el); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment