Skip to content

Instantly share code, notes, and snippets.

@Nicanor008
Last active July 28, 2020 21:11
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 Nicanor008/4185a8c5edbbb031d75c5ecde4f57356 to your computer and use it in GitHub Desktop.
Save Nicanor008/4185a8c5edbbb031d75c5ecde4f57356 to your computer and use it in GitHub Desktop.
Get the current device dimensions. Either width or hight in react
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