Last active
April 17, 2020 11:29
-
-
Save lou/e4f1e605f5552206e24cbbd85abb9ccb to your computer and use it in GitHub Desktop.
Storybook Iframe height
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
// App side | |
import React, { useEffect, useRef, SyntheticEvent } from "react" | |
type IframePropsType = { | |
src: string | |
} | |
export default ({ src }: IframePropsType) => { | |
const el = useRef<HTMLIFrameElement>(null) | |
useEffect(() => { | |
window.addEventListener("message", handleMessage) | |
}, []) | |
const handleLoad = (e: SyntheticEvent<HTMLIFrameElement, UIEvent>) => { | |
if (e.currentTarget?.contentWindow) | |
e.currentTarget.contentWindow.postMessage("getDocumentHeight", "*") | |
} | |
const handleMessage = (e: MessageEvent) => { | |
if (el.current && e.data.documentHeight) { | |
el.current.style.height = `${e.data.documentHeight}px` | |
} | |
} | |
return <iframe src={src} onLoad={handleLoad} ref={el} /> | |
} |
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
// Storybook side | |
// src/decorators/PostDocumentHeight.tsx | |
import React, { useEffect } from "react" | |
const PostDocumentHeight = ({ children }) => { | |
useEffect(() => { | |
window.addEventListener("message", function(e) { | |
if ( | |
e.data === "getDocumentHeight" && | |
e.source && | |
!(e.source instanceof MessagePort) && | |
!(e.source instanceof ServiceWorker) | |
) { | |
e.source.postMessage( | |
{ documentHeight: document.documentElement.scrollHeight }, | |
"*" | |
) | |
} | |
}) | |
}, []) | |
return <>{children}</> | |
} | |
export default PostDocumentHeight |
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
// Storybook side | |
// .storybook/config.js | |
import React from "react" | |
import { addDecorator } from "@storybook/react" | |
import PostDocumentHeight from "../src/decorators/PostDocumentHeight" | |
const PostDocumentHeightDecorator = storyFn => ( | |
<PostDocumentHeight>{storyFn()}</PostDocumentHeight> | |
) | |
addDecorator(PostDocumentHeightDecorator) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment