Skip to content

Instantly share code, notes, and snippets.

@qti3e
Created January 28, 2018 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qti3e/b18a5d436402e64701387fe672c1cd0b to your computer and use it in GitHub Desktop.
Save qti3e/b18a5d436402e64701387fe672c1cd0b to your computer and use it in GitHub Desktop.
withWindowDimensions React.js HOC
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