Last active
November 15, 2017 01:40
-
-
Save saadtazi/17de1ecf0b9c265690d1414da88e3e5c to your computer and use it in GitHub Desktop.
WindowResizeListener
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
class ResizeListener extends React.Component { | |
state = {} | |
getWindowSize() { | |
return { | |
innerWidth: window.innerWidth, | |
innerHeight: window.innerHeight, | |
}; | |
} | |
changeState = () => { | |
const newSize = this.getWindowSize(); | |
this.setState(newSize); | |
this.props.onChange(newSize); | |
} | |
componentDidMount() { | |
this.changeState(); | |
window.addEventListener('resize', this.changeState, true); | |
} | |
componentWillUnmount() { | |
window.removeEventListener('resize', this.changeState, true); | |
} | |
render() { | |
return <span data-innerwidth={this.state.innerWidht} data-innerheight={this.state.innerHeight}/>; | |
} | |
} | |
class MyComponent extends React.Component { | |
state = {} | |
handleWindowChange = (size) => { | |
this.setState(size); | |
} | |
render() { | |
return ( | |
<div> | |
<ResizeListener onChange={this.handleWindowChange}/> | |
<h1>windowSize: {this.state.innerWidth} x {this.state.innerHeight}</h1> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render( | |
<MyComponent/>, | |
document.getElementById('container') | |
); |
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
const withWindowSize = (WrappedComponent) => { | |
class ResizeListener extends React.Component { | |
state = {} | |
getWindowSize() { | |
return { | |
innerWidth: window.innerWidth, | |
innerHeight: window.innerHeight, | |
}; | |
} | |
changeState = () => { | |
this.setState(this.getWindowSize()); | |
} | |
componentDidMount() { | |
this.changeState(); | |
window.addEventListener('resize', this.changeState, true); | |
} | |
componentWillUnmount() { | |
window.removeEventListener('resize', this.changeState, true); | |
} | |
render() { | |
return <WrappedComponent {...this.props} {...this.state} />; | |
} | |
} | |
return ResizeListener; | |
} | |
const myComponent = ({a}) => { | |
return <h1>windowSize: {innerWidth} x {innerHeight}</h1> | |
} | |
const MyWrappedComponent = withWindowSize(myComponent); | |
ReactDOM.render( | |
<MyWrappedComponent/>, | |
document.getElementById('container') | |
); |
One option: use https://github.com/ctrlplusb/react-sizeme on the container and inject its width/height to the component that renders the canvas (idea from https://github.com/alampros/react-confetti)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Really depends on the usecase.