Skip to content

Instantly share code, notes, and snippets.

@lokhmakov
Created May 14, 2017 08:48
Show Gist options
  • Save lokhmakov/ed4d6d2787fdf9b733e5b54acc104907 to your computer and use it in GitHub Desktop.
Save lokhmakov/ed4d6d2787fdf9b733e5b54acc104907 to your computer and use it in GitHub Desktop.
import React from 'react'
function withWindowSize(WrappedComponent) {
return class WindowSizeProvider extends React.Component {
constructor(props) {
super(props)
this.state = {
innerWidth: 1280,
innerHeight: 800,
show: false,
}
}
onWindowResize = () => {
if (!this.mounted) return
this.setState({
innerWidth: window.innerWidth,
innerHeight: window.innerHeight,
})
}
componentDidMount() {
this.mounted = true
window.addEventListener('resize', this.onWindowResize)
this.onWindowResize()
this.setState({ show: true })
}
componentWillUnmount() {
this.mounted = false
window.removeEventListener('resize', this.onWindowResize);
}
render() {
const { show } = this.state
if (!show) return null
return (
<WrappedComponent
{ ...this.props }
{ ...this.state }
/>
)
}
}
}
export default withWindowSize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment