Skip to content

Instantly share code, notes, and snippets.

@gunn
Last active May 4, 2023 15:47
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save gunn/16e8387b1a02d9f0aeb8c1e73f2ea6cc to your computer and use it in GitHub Desktop.
Save gunn/16e8387b1a02d9f0aeb8c1e73f2ea6cc to your computer and use it in GitHub Desktop.
Render react content in an iframe
import * as React from 'react'
import { createPortal } from 'react-dom'
type FrameProps = React.IframeHTMLAttributes<HTMLIFrameElement> & {
head?: React.ComponentType<any>
children?: React.ReactNode
}
const Frame = React.memo(({head, children, ...iframeProps}: FrameProps)=> {
const node = React.useRef<HTMLIFrameElement>()
const [doc, setDoc] = React.useState<Document>()
React.useEffect(()=> {
setDoc(node.current.contentDocument)
}, [])
return (
<iframe {...iframeProps} ref={node}>
{ doc && createPortal(head, doc.head) }
{ doc && createPortal(children, doc.body) }
</iframe>
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment