Created
March 22, 2018 00:25
-
-
Save pedrouid/ac66272c1cd1ec03d95a34361c1d5d7c to your computer and use it in GitHub Desktop.
Window Responsiveness React High Order Component
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, { Component } from 'react'; | |
| function windowResize(WrappedComponent) { | |
| return class extends Component { | |
| state = { | |
| width: '', | |
| height: '' | |
| }; | |
| updateDimensions = () => { | |
| const w = typeof window !== 'undefined' ? window : ''; | |
| const d = typeof window !== 'undefined' ? document : ''; | |
| const documentElement = d ? d.documentElement : ''; | |
| const body = d ? d.body || d.getElementsByTagName('body')[0] : ''; | |
| const width = w.innerWidth || documentElement.clientWidth || body.clientWidth; | |
| const height = w.innerHeight || documentElement.clientHeight || body.clientHeight; | |
| this.setState({ width, height }); | |
| }; | |
| componentWillMount() { | |
| this.updateDimensions(); | |
| } | |
| componentDidMount() { | |
| window.addEventListener('resize', this.updateDimensions); | |
| } | |
| componentWillUnmount() { | |
| window.removeEventListener('resize', this.updateDimensions); | |
| } | |
| render = () => ( | |
| <WrappedComponent width={this.state.width} height={this.state.height} {...this.props} /> | |
| ); | |
| }; | |
| } | |
| export default windowResize; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment