Using Hooks (React 16.8.0+)
Create a useWindowDimensions hook.
***
import { useState, useEffect } from 'react';
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
}
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
}
***
And after that you'll be able to use it in your components like this
***
const Component = () => {
const { height, width } = useWindowDimensions();
return (
width: {width} ~ height: {height}
);
}
***