Skip to content

Instantly share code, notes, and snippets.

@tluyben
Created February 4, 2022 16:51
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 tluyben/7ea69ed68a4d17ac73d495b63322ebe8 to your computer and use it in GitHub Desktop.
Save tluyben/7ea69ed68a4d17ac73d495b63322ebe8 to your computer and use it in GitHub Desktop.
React iframe rendering
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