Skip to content

Instantly share code, notes, and snippets.

@saadtazi
Last active November 15, 2017 01:40
Show Gist options
  • Save saadtazi/17de1ecf0b9c265690d1414da88e3e5c to your computer and use it in GitHub Desktop.
Save saadtazi/17de1ecf0b9c265690d1414da88e3e5c to your computer and use it in GitHub Desktop.
WindowResizeListener
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')
);
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')
);
@saadtazi
Copy link
Author

  • withWindowSize: not ideal if more than one component needs to get notified on resize... A better approach would be: react context with withWindowSize.js (+ a WindowSizeProvider component...): only one resize event handler...
  • resize-aware.js: could work with redux if size needs to be in redux state... not extra clean approach....

Really depends on the usecase.

@saadtazi
Copy link
Author

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