Skip to content

Instantly share code, notes, and snippets.

@eai04191
Created February 17, 2021 15:04
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 eai04191/29c5c7b0dd4b16c77e57266f7e26a249 to your computer and use it in GitHub Desktop.
Save eai04191/29c5c7b0dd4b16c77e57266f7e26a249 to your computer and use it in GitHub Desktop.
React Iframe for writing to contentDocument with hook.
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