React createPortal not rendering component inside iframe properly

278 Views Asked by At

I have a React component using the iframe element along with createPortal.


import React, {ReactNode, useState} from 'react'
import { createPortal } from 'react-dom'

type Props = {
    children?: ReactNode
}

export const IFrame = (props: Props) => {
    const [ref, setRef] = useState<HTMLIFrameElement | null>()
    const container = ref?.contentDocument?.body
    
    return (
        <iframe ref={setRef}>
            {container && createPortal(props.children, container)}
        </iframe>
    )
}

I can use the IFrame component with another component.

<IFrame><div>Hello, World!</div></IFrame>

But what I see inside the iframe when it renders, is only a breif flash with the text Hello, World! before it disappears.

Why is the iframe removing the content after render?

Here is the React versions I am using:

"react": "^18.2.0",
"react-dom": "^18.2.0",
0

There are 0 best solutions below