Joyful Games – iPhone game development with Apple’s Swift new language

Email Contact

Play SnakeJoy! The most addicting fun snake game on the internet

Play SnakeJoy in Your Browser!

React Styled Components in IFrames

How can you use Styled Components inside an IFrame? It took some research, but I found an elegant solution using styled-components and react-frame-component.

Happily, styled-components includes a StyleSheetManager component that can take a target prop. The target expects a DOM node, and it will attach its dynamically created stylesheets to that node.

react-frame-component uses React’s new version of its Context API to expose a FrameContextProvider. It includes the IFrame document and window in the context.

You can combine these two APIs as follows to use styled-components inside your IFrames:

      frameContext => (
        <StyleSheetManager target={frameContext.document.head}>
            {/* your children here */}

This works perfectly with react v16.4.1, styled-components v3.3.3, and react-frame-component v4.0.0.