Skip to content

Instantly share code, notes, and snippets.

@vahidd
Created August 20, 2018 06:36
Show Gist options
  • Select an option

  • Save vahidd/66d11f1e9171c3e82a8f7c99c73e6229 to your computer and use it in GitHub Desktop.

Select an option

Save vahidd/66d11f1e9171c3e82a8f7c99c73e6229 to your computer and use it in GitHub Desktop.
This HOC renders the inner component on page resize. (Note that this hoc requires lodash in your project)
import React from 'react';
import debounce from 'lodash/debounce';
/**
* Usage example:
* export default rerenderOnResize()(Header);
*/
export default () => (WrappedComponent) => {
class ReRenderOnResize extends React.PureComponent {
componentDidMount() {
this.callback = debounce(this.rerender, 100);
window.addEventListener('resize', this.callback);
}
componentWillUnmount() {
window.removeEventListener('resize', this.callback);
}
rerender = () => {
this.forceUpdate();
};
render() {
const props = { ...this.props };
return <WrappedComponent {...props} />;
}
}
return ReRenderOnResize;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment