Created
January 14, 2021 10:57
-
-
Save Rem0ld/7972eb01e73bae6ae7738b3e2982897d to your computer and use it in GitHub Desktop.
React hook to get the dimensions of the window
This file contains hidden or 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 { useState, useEffect } from "react"; | |
function getWindowDimensions() { | |
const { innerWidth: width, innerHeight: height } = window; | |
return { | |
width, | |
height, | |
}; | |
} | |
export default function useWindowDimension() { | |
const [windowDimensions, setWindowDimensions] = useState( | |
getWindowDimensions() | |
); | |
useEffect(() => { | |
function handleResize() { | |
setWindowDimensions(getWindowDimensions()); | |
} | |
window.addEventListener("resize", handleResize); | |
return () => window.removeEventListener("resize", handleResize); | |
}, []); | |
return windowDimensions; | |
} | |
// Found at: https://stackoverflow.com/questions/36862334/get-viewport-window-height-in-reactjs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment