Created
May 14, 2017 08:48
-
-
Save lokhmakov/ed4d6d2787fdf9b733e5b54acc104907 to your computer and use it in GitHub Desktop.
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 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