Skip to content

Instantly share code, notes, and snippets.

@jstcki
Last active September 18, 2017 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstcki/1132a1181e8950864003620ca3426f04 to your computer and use it in GitHub Desktop.
Save jstcki/1132a1181e8950864003620ca3426f04 to your computer and use it in GitHub Desktop.
React 16 Portal
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
// Portal into a DOM element with ID 'sidebar'
const Sidebar = ({ children }) =>
ReactDOM.createPortal(children, document.getElementById("sidebar"));
// Portal into a dynamically created iframe
class IFrame extends React.Component {
state = { portalTarget: null };
componentDidMount() {
const doc = this.iframe.contentDocument;
const t = doc.createElement("div");
doc.body.appendChild(t);
this.setState({ portalTarget: t });
}
render() {
return (
<iframe
ref={el => {
this.iframe = el;
}}
>
{this.state.portalTarget &&
ReactDOM.createPortal(
React.Children.only(this.props.children),
this.state.portalTarget
)}
</iframe>
);
}
}
const App = () => (
<div>
<h1>Hello</h1>
<Sidebar>hellohello</Sidebar>
<IFrame>
<div>Ayy macarena</div>
</IFrame>
<Sidebar>
<IFrame>
<div>Ayy portall</div>
</IFrame>
</Sidebar>
</div>
);
ReactDOM.render(<App />, document.getElementById("root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment