Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@antenando
Forked from robertgonzales/Frame.js
Created December 12, 2017 12:44
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 antenando/6300fa16ca1906fd27122ed345f08be4 to your computer and use it in GitHub Desktop.
Save antenando/6300fa16ca1906fd27122ed345f08be4 to your computer and use it in GitHub Desktop.
Use React portals to render inside shadow dom and iframes
class Frame extends Component {
componentDidMount() {
this.iframeHead = this.node.contentDocument.head
this.iframeRoot = this.node.contentDocument.body
this.forceUpdate()
}
render() {
const { children, head, ...rest } = this.props
return (
<iframe {...rest} ref={node => (this.node = node)}>
{this.iframeHead && ReactDOM.createPortal(head, this.iframeHead)}
{this.iframeRoot && ReactDOM.createPortal(children, this.iframeRoot)}
</iframe>
)
}
}
<Frame head={<title>Hello World</title>}>
<h1>Hello World</h1>
</Frame>
class Shadow extends Component {
componentDidMount() {
this.shadowRoot = this.node.attachShadow({ mode: this.props.mode })
this.forceUpdate()
}
render() {
const { children, ...rest } = this.props
return (
<div {...rest} ref={node => (this.node = node)}>
{this.shadowRoot && ReactDOM.createPortal(children, this.shadowRoot)}
</div>
)
}
}
<Shadow mode="open">
<h1>Hello World</h1>
</Shadow>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment