Skip to content

Instantly share code, notes, and snippets.

@tluyben
Created Feb 4, 2022
Embed
What would you like to do?
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