Forward style of nextJS app in a React Portal

Viewed 456

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!

1 Answers

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.

Related