Skip to content

Instantly share code, notes, and snippets.

@ccurtin
Forked from ptb/VisualViewport.jsx
Created July 12, 2022 20:33
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 ccurtin/ec647c87b2893ed18d2191b9d710ab98 to your computer and use it in GitHub Desktop.
Save ccurtin/ec647c87b2893ed18d2191b9d710ab98 to your computer and use it in GitHub Desktop.
import React, { useEffect, useRef, useState } from "react"
export const VisualViewport = ({
as: Element = "div",
children,
style = {},
...props
}) => {
const ref = useRef (null)
const [viewport, setViewport] = useState ({
"maxHeight": "100vh",
"maxWidth": "100vw"
})
const updateViewport = () => {
setViewport ({
"maxHeight": window.visualViewport.height,
"maxWidth": window.visualViewport.width
})
window.scrollTo (0, ref.current.offsetTop)
}
useEffect (() => {
if (
typeof window !== "undefined"
&& typeof window.visualViewport !== "undefined"
) {
updateViewport ()
window.visualViewport.addEventListener ("resize", updateViewport)
return () =>
window.visualViewport.removeEventListener ("resize", updateViewport)
}
}, [])
return (
<Element
ref={ref}
style={{ ...style, ...viewport }}
{...props}
>
{children}
</Element>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment