Last active
November 4, 2020 22:42
-
-
Save psenger/fcf809f3c1912a19c85fd0763bfa68ea to your computer and use it in GitHub Desktop.
[Responsive Window Resize Event with ReactJS] #ReactJs #JavaScript
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 React from "react"; | |
| function someResponsiveComponent() { | |
| const {height,width} = windowResizeEventListener(); | |
| return ( | |
| <p> | |
| The window <span>height = {height}</span><span>width = {width}</span> | |
| </p> | |
| ); | |
| } |
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 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