Skip to content

Instantly share code, notes, and snippets.

@yoavniran
Created July 25, 2019 08:55
Show Gist options
  • Save yoavniran/0953eff3d88f385431b9decc0c3a6be5 to your computer and use it in GitHub Desktop.
Save yoavniran/0953eff3d88f385431b9decc0c3a6be5 to your computer and use it in GitHub Desktop.
PreviewLayout for Gatsby & Netlify CMS to enable styled-components
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