Skip to content

Instantly share code, notes, and snippets.

@mka142
Created July 7, 2022 21:56
Show Gist options
  • Save mka142/eac405d3b9cac08a8fb8f14fa267fbb8 to your computer and use it in GitHub Desktop.
Save mka142/eac405d3b9cac08a8fb8f14fa267fbb8 to your computer and use it in GitHub Desktop.
React portal class component
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