import {createPortal} from 'react-dom'; import {createRoot} from 'react-dom/client'; import {useEffect, useRef} from 'react'; import './styles.scss'; /** * @since 3.14.0 * Creates a portal to the Top Level document, rendering children elements within an iframe. */ export default function createIframePortal(children, targetElement = window.top.document.body) { const iframeRef = useRef(null); const rootRef = useRef(null); useEffect(() => { const iframe = iframeRef.current; if (!iframe) return; // Wait for iframe to be ready const setupIframe = () => { const iframeDoc = iframe.contentDocument || iframe.contentWindow.document; // Clear existing content iframeDoc.open(); iframeDoc.write(''); iframeDoc.close(); async function renderContent() { try { await fetchStylesheets(iframeDoc); // Create a container in the iframe const iframeContainer = iframeDoc.createElement('div'); iframeContainer.id = 'givewp-fields-consent-iframe-container'; iframeDoc.body.appendChild(iframeContainer); // Create root and render rootRef.current = createRoot(iframeContainer); rootRef.current.render(children); } catch (error) { console.error('Error loading stylesheets:', error); } } renderContent(); }; iframe.onload = setupIframe; if (iframe.contentDocument?.readyState === 'complete') { setupIframe(); } }, [children, targetElement]); return createPortal(