Last active
September 18, 2017 13:49
-
-
Save jstcki/1132a1181e8950864003620ca3426f04 to your computer and use it in GitHub Desktop.
React 16 Portal
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"; | |
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