Created
February 17, 2021 15:04
-
-
Save eai04191/29c5c7b0dd4b16c77e57266f7e26a249 to your computer and use it in GitHub Desktop.
React Iframe for writing to contentDocument with hook.
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 { useEffect, useRef } from "react"; | |
export const CustomIframe = ({ html }: { html: string }): JSX.Element => { | |
const iframeRef = useRef<HTMLIFrameElement | null>(null); | |
// rewrite document when html changed. | |
useEffect(() => { | |
if (!iframeRef.current) return; | |
const doc = iframeRef.current.contentDocument; | |
doc.open(); | |
doc.write(html); | |
doc.close(); | |
}, [html]); | |
return <iframe src="about:blank" ref={iframeRef} />; | |
}; | |
const App = (): JSX.Element => { | |
const html = `<h1>Hello Iframe</h1>`; | |
return <CustomIframe html={html} />; | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment