Last active
October 13, 2017 19:21
-
-
Save rabet/af318bdc3c7bee5fe08237e29c39e9a6 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, { Component } from 'react' | |
import ReactDOM from 'react-dom' | |
import debounce from 'lodash/debounce' | |
class AutoSizer extends Component { | |
constructor() { | |
super() | |
this.getWidthAndHeight = debounce(this.getWidthAndHeight.bind(this), 200) | |
this.state = { | |
width: 0, | |
height: 0 | |
} | |
} | |
// adding the listener for window resize | |
componentDidMount() { | |
this.getWidthAndHeight() | |
window.addEventListener('resize', this.getWidthAndHeight) | |
} | |
// removing the listener when component unmounts | |
componentWillUnmount() { | |
window.removeEventListener('resize', this.getWidthAndHeight) | |
} | |
getWidthAndHeight() { | |
this.setState({ | |
width: window.innerWidth, | |
height: window.innerHeight | |
}) | |
} | |
// returning the children as a function with object as argument, so I can render this function as the children of AutoSizer | |
render() { | |
return this.props.children({ width: this.state.width, height: this.state.height }) | |
} | |
} | |
ReactDOM.render( | |
<AutoSizer> | |
{({ width, height }) => <div>{`${width} x ${height}`}</div>} | |
</AutoSizer>, | |
document.getElementById('root') | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment