Skip to content

Instantly share code, notes, and snippets.

@khades
Created June 19, 2019 08:23
Show Gist options
  • Save khades/c37368f9a270e0e5c9476854d2366c20 to your computer and use it in GitHub Desktop.
Save khades/c37368f9a270e0e5c9476854d2366c20 to your computer and use it in GitHub Desktop.
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