Skip to content

Instantly share code, notes, and snippets.

@condor-bird
Created April 4, 2020 08:42
Show Gist options
  • Save condor-bird/bfc097ebc2e271b95642153df1c17ee3 to your computer and use it in GitHub Desktop.
Save condor-bird/bfc097ebc2e271b95642153df1c17ee3 to your computer and use it in GitHub Desktop.
Rerender view on browser resize with React
import React, { useLayoutEffect, useState } from 'react';
function useWindowSize() {
const [size, setSize] = useState([0, 0]);
useLayoutEffect(() => {
function updateSize() {
setSize([window.innerWidth, window.innerHeight]);
}
window.addEventListener('resize', updateSize);
updateSize();
return () => window.removeEventListener('resize', updateSize);
}, []);
return size;
}
function ShowWindowDimensions(props) {
const [width, height] = useWindowSize();
return <span>Window size: {width} x {height}</span>;
}
///
import React from 'react';
class ShowWindowDimensions extends React.Component {
state = { width: 0, height: 0 };
render() {
return <span>Window size: {this.state.width} x {this.state.height}</span>;
}
updateDimensions = () => {
this.setState({ width: window.innerWidth, height: window.innerHeight });
};
componentDidMount() {
window.addEventListener('resize', this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimensions);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment