Last active
February 14, 2024 14:52
-
-
Save ptb/9ace4534d67393683bf7191370a16089 to your computer and use it in GitHub Desktop.
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
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