Last active
July 28, 2020 21:11
-
-
Save Nicanor008/4185a8c5edbbb031d75c5ecde4f57356 to your computer and use it in GitHub Desktop.
Get the current device dimensions. Either width or hight in react
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, useState } from "react" | |
function getWindowDimensions() { | |
const { innerWidth: width, innerHeight: height } = window; | |
return { | |
width, | |
height | |
}; | |
} | |
export default function useWindowDimensions() { | |
const [windowDimensions, setWindowDimensions] = useState( | |
getWindowDimensions() | |
); | |
useEffect(() => { | |
function handleResize() { | |
setWindowDimensions(getWindowDimensions()); | |
} | |
window.addEventListener("resize", handleResize); | |
return () => window.removeEventListener("resize", handleResize); | |
}, []); | |
return windowDimensions; | |
} | |
const Component = () => { | |
const { height, width } = useWindowDimensions(); | |
return ( | |
<div> | |
width: {width} ~ height: {height} | |
</div> | |
); | |
}; | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<Component />, rootElement); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment