Created
January 28, 2018 12:11
-
-
Save qti3e/b18a5d436402e64701387fe672c1cd0b to your computer and use it in GitHub Desktop.
withWindowDimensions React.js HOC
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, {Component} from 'react' | |
import hoistNonReactStatic from 'hoist-non-react-statics' | |
export default function(WrappedComponent){ | |
class withWindowDimensions extends Component{ | |
constructor(props){ | |
super(props) | |
this.updateDimensions = this.updateDimensions.bind(this) | |
} | |
updateDimensions(){ | |
this.setState({ | |
width: window.innerWidth, | |
height: window.innerHeight | |
}) | |
} | |
componentDidMount(){ | |
window.addEventListener("resize", this.updateDimensions) | |
} | |
componentWillUnmount(){ | |
window.removeEventListener("resize", this.updateDimensions) | |
} | |
componentWillMount(){ | |
this.updateDimensions() | |
} | |
render(){ | |
return ( | |
<WrappedComponent | |
windowWidth={this.state.width} | |
windowHeight={this.state.height} | |
{...this.props} | |
/> | |
) | |
} | |
} | |
withWindowDimensions.displayName = `withWindowDimensions(${getDisplayName(WrappedComponent)})` | |
hoistNonReactStatic(withWindowDimensions, WrappedComponent) | |
return withWindowDimensions | |
} | |
function getDisplayName(WrappedComponent) { | |
return WrappedComponent.displayName || WrappedComponent.name || 'Component' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment