Skip to content

Instantly share code, notes, and snippets.

@lou

lou/0_iframe.tsx

Last active Apr 17, 2020
Embed
What would you like to do?
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