3

I'm developing an app with next.js and for one purpose, I need to use React portals within iframes. As found there https://stackoverflow.com/a/34744946/5860648, it works great: my components are rendered in the iframe and interacting with the whole app even though it is not in the same page.

Only one thing remains: next.js automatically inserts the style in my root web page.

I'd like to get that style and copy/forward it into the iframe, so that the content inside the portal uses the style I make.

I found nothing out of the documentation or the web to do this properly... so if any one has already found a good trick, it would be really helpful!

Thanks!

sjahan
  • 5,720
  • 3
  • 19
  • 42
  • 1
    What kind of styling solution do you use? Next.js' CSS-Modules or styled-jsx? Something else entirely? In the answer you linked is a CodeSandbox which shows off some recipes how to get your styles injected into your iframe, but it hugely depends on he approach you're taking. – Lukas Bünger Apr 20 '21 at 07:27
  • @LukasBünger I'm using standard CSS Modules for that! I did something that works so far, going to publish it soon! – sjahan Apr 21 '21 at 08:06

1 Answers1

2

Here is what I'm doing so far, feel free to reuse it or submit a better idea :)

const completeStyle = () => {
      let style = "";
      for (let styleSheet of document.styleSheets) {
        try {
          if (styleSheet.cssRules) {
            for (let cssRule of styleSheet.cssRules) {
              style += cssRule.cssText;
            }
          }
        } catch (e) {}
      }
      return style;
};

Basically, I scan the whole stylesheets loaded in my main page, concatenate each cssRules available and inject that in a <style> tag. It works fine so far.

sjahan
  • 5,720
  • 3
  • 19
  • 42