Skip to content

Instantly share code, notes, and snippets.

@stevemu
Created May 4, 2019 21:34
Show Gist options
  • Save stevemu/fa76c410684a8eeedaa2e93bb53cb7bc to your computer and use it in GitHub Desktop.
Save stevemu/fa76c410684a8eeedaa2e93bb53cb7bc to your computer and use it in GitHub Desktop.
a HOC for react that inject height and weight of window in a component, good for the use-case that you need to show or hide something depend on the size of the window
import React from 'react';
function withResizeAware(WrappedComponent) {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
height: document.documentElement.clientHeight,
width: document.documentElement.clientWidth
}
}
componentDidMount() {
window.addEventListener("resize", this.handleResize);
}
componentWillUnmount() {
window.removeEventListener("resize", this.handleResize);
}
handleResize = (e) => {
this.setState({
height: document.documentElement.clientHeight,
width: document.documentElement.clientWidth
})
}
render() {
return (
<div>
<WrappedComponent height={this.state.height} width={this.state.width} {...this.props} />
</div>
);
}
}
}
export default withResizeAware;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment