Skip to content

Instantly share code, notes, and snippets.

@lou
Last active April 17, 2020 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lou/e4f1e605f5552206e24cbbd85abb9ccb to your computer and use it in GitHub Desktop.
Save lou/e4f1e605f5552206e24cbbd85abb9ccb to your computer and use it in GitHub Desktop.
Storybook Iframe height
// 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} />
}
// 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
// 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