2

I am trying to put some react components inside an Iframe, and I have succeeded to do that, I followed this way: How to set iframe content of a react component.

But I faced many problems, it's like the component stays connected with the iframe parent, when I try to get the document of the component, I found that it return the document of the parent not the document of the iframe.

For example, I have this Iframe where I call the CustomeComponent inside the Iframe.

const IframeComponents: React.FC<SomerProps> = ({ children = null, ...props }) => {
  const contentRef = React.useRef<HTMLIFrameElement>(null)
  const [mountNode, setMountNode] = React.useState<HTMLElement>()

  useEffect(() => {
    const doc = contentRef?.current?.contentWindow?.document
  
    if (doc) {
      setMountNode(doc.body);
    }
  }, [children])

  return (
    <iframe id="editor-iframe" {...props} ref={contentRef}>
      {mountNode && createPortal(<CustomeComponent>{children}</CustomeComponent>, mountNode)}
    </iframe>
  )
}

And inside the CustomeComponent.tsx I have this script:

useEffect(() => {
    console.log(document) // <== here I get the document of the iframe parent
    // if I want to access to the iframe document 
    console.log(window.frames[0].document) // <== this works well
}, [children])

Here is a small example of what I said,

enter image description here

is there any solution for this problem?

Nouh Belahcen
  • 774
  • 1
  • 11
  • 36

0 Answers0