Skip to content

Instantly share code, notes, and snippets.

@psenger
Last active November 4, 2020 22:42
Show Gist options
  • Select an option

  • Save psenger/fcf809f3c1912a19c85fd0763bfa68ea to your computer and use it in GitHub Desktop.

Select an option

Save psenger/fcf809f3c1912a19c85fd0763bfa68ea to your computer and use it in GitHub Desktop.
[Responsive Window Resize Event with ReactJS] #ReactJs #JavaScript
import React from "react";
function someResponsiveComponent() {
const {height,width} = windowResizeEventListener();
return (
<p>
The window <span>height = {height}</span><span>width = {width}</span>
</p>
);
}
import React, {useEffect,useState} from "react";
/**
* This component makes available the window resize event with height and width
* @return {{width: number, height: number}}
*/
function windowResizeEventListener() {
const [width, setWindowWidth] = useState(window.innerWidth);
const [height, setWindowHeight] = useState(window.innerHeight);
useEffect(() => {
const onResize = () => {
setWindowWidth(window.innerWidth);
setWindowHeight(window.innerHeight);
};
window.addEventListener('resize', onResize);
return () => {
window.removeEventListener('resize', onResize);
};
});
return {width,height};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment