Created
July 25, 2019 08:55
-
-
Save yoavniran/0953eff3d88f385431b9decc0c3a6be5 to your computer and use it in GitHub Desktop.
PreviewLayout for Gatsby & Netlify CMS to enable styled-components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useRef, useLayoutEffect } from "react"; | |
import { StyleSheetManager } from "styled-components"; | |
import PreviewContext from "./PreviewContext"; | |
const WithPreviewContext = ({ children }) => | |
<PreviewContext.Provider value={true}> | |
<main> | |
{children} | |
</main> | |
</PreviewContext.Provider>; | |
const PreviewLayout = ({ children }) => { | |
const iframeRef = useRef(null); | |
useLayoutEffect(() => { | |
const iframe = document.querySelector('#nc-root iframe'); | |
const iframeHeadElem = iframe && iframe.contentDocument.head; | |
iframeRef.current = iframeHeadElem; | |
}); | |
return iframeRef && iframeRef.current ? | |
<StyleSheetManager target={iframeRef.current}> | |
<WithPreviewContext> | |
{children} | |
</WithPreviewContext> | |
</StyleSheetManager> : | |
<WithPreviewContext> | |
{children} | |
</WithPreviewContext>; | |
}; | |
export default PreviewLayout; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment