Created
May 4, 2019 21:34
-
-
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
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 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