Created
June 19, 2019 08:23
-
-
Save khades/c37368f9a270e0e5c9476854d2366c20 to your computer and use it in GitHub Desktop.
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 from 'react'; | |
import throttle from 'lodash/throttle'; | |
class WidthListener extends React.PureComponent { | |
width = 0; | |
constructor(props) { | |
super(props); | |
this.onWidthChangeThrottled = throttle(this.onWidthChange, 200); | |
} | |
componentDidMount() { | |
this.onWidthChangeThrottled(); | |
window.addEventListener('resize', this.onWidthChangeThrottled); | |
window.addEventListener('orientationchange', this.onWidthChange); | |
} | |
componentWillUnmount() { | |
window.removeEventListener('resize', this.onWidthChangeThrottled); | |
window.removeEventListener('orientationchange', this.onWidthChange); | |
} | |
onWidthChange = () => { | |
if (this.width === window.innerWidth) { | |
return; | |
} | |
this.width = window.innerWidth; | |
const { onWidthChange } = this.props; | |
onWidthChange(window.innerWidth); | |
}; | |
render() { | |
return null; | |
} | |
} | |
export default WidthListener; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment