Created
April 4, 2020 08:42
-
-
Save condor-bird/bfc097ebc2e271b95642153df1c17ee3 to your computer and use it in GitHub Desktop.
Rerender view on browser resize with React
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, { useLayoutEffect, useState } from 'react'; | |
function useWindowSize() { | |
const [size, setSize] = useState([0, 0]); | |
useLayoutEffect(() => { | |
function updateSize() { | |
setSize([window.innerWidth, window.innerHeight]); | |
} | |
window.addEventListener('resize', updateSize); | |
updateSize(); | |
return () => window.removeEventListener('resize', updateSize); | |
}, []); | |
return size; | |
} | |
function ShowWindowDimensions(props) { | |
const [width, height] = useWindowSize(); | |
return <span>Window size: {width} x {height}</span>; | |
} | |
/// | |
import React from 'react'; | |
class ShowWindowDimensions extends React.Component { | |
state = { width: 0, height: 0 }; | |
render() { | |
return <span>Window size: {this.state.width} x {this.state.height}</span>; | |
} | |
updateDimensions = () => { | |
this.setState({ width: window.innerWidth, height: window.innerHeight }); | |
}; | |
componentDidMount() { | |
window.addEventListener('resize', this.updateDimensions); | |
} | |
componentWillUnmount() { | |
window.removeEventListener('resize', this.updateDimensions); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment