React에서 iframe 내부에 컴포넌트 렌더링

// react-frame-component 사용 (권장)
import Frame from 'react-frame-component'
;<Frame head={<style>{`body { margin: 0; }`}</style>}>
  <MyComponent />
</Frame>

// 직접 구현: createPortal + contentDocument
function IframeRenderer({ children }) {
  const iframeRef = useRef<HTMLIFrameElement>(null)
  const [mountNode, setMountNode] = useState<HTMLElement | null>(null)
  useEffect(() => {
    const iframe = iframeRef.current
    const handleLoad = () => setMountNode(iframe?.contentDocument?.body ?? null)
    iframe?.addEventListener('load', handleLoad)
    if (iframe?.contentDocument?.readyState === 'complete') handleLoad()
    return () => iframe?.removeEventListener('load', handleLoad)
  }, [])
  return (
    <>
      <iframe ref={iframeRef} />
      {mountNode && createPortal(children, mountNode)}
    </>
  )
}

iframe 내부는 부모 CSS 미적용 (스타일 별도 주입 필요), DOM 이벤트는 iframe 밖으로 버블링 안 됨 — 단 React 핸들러는 portal 이라 React 트리를 따라 부모로 올라온다1. 단순 스타일 격리 목적이면 Shadow DOM 고려.


Footnotes

  1. createPortal – React: “Events from portals propagate according to the React tree rather than the DOM tree.” ↩

`#506`