Created
February 4, 2022 16:51
-
-
Save tluyben/7ea69ed68a4d17ac73d495b63322ebe8 to your computer and use it in GitHub Desktop.
React iframe rendering
This file contains 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, { createRef } from "react"; | |
import ReactDOM from "react-dom"; | |
export default class Frame extends React.Component { | |
constructor(props) { | |
super(props) | |
this.ref = createRef() | |
} | |
render() { | |
return <iframe ref={this.ref}></iframe> | |
} | |
componentDidMount() { | |
this.renderFrameContents() | |
} | |
componentDidUpdate() { | |
this.renderFrameContents() | |
} | |
// ? | |
componentWillUnmount() { | |
ReactDOM.unmountComponentAtNode(this.ref.current?.contentDocument.body) | |
} | |
renderFrameContents() { | |
const doc = this.ref.current?.contentDocument | |
if(doc?.readyState === 'complete' && this.props.children) { | |
ReactDOM.render(this.props.children, doc.body) | |
} else { | |
setTimeout(this.renderFrameContents, 0); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment