To get the window screen width and height in React:
jsximport React, { useEffect, useState } from 'react'; const Component = () => { const [dimensions, setDimensions] = useState(null); useEffect(() => { setDimensions({ width: window.screen.width, height: window.screen.height }); }, []); return( <div>Window width is {dimensions?.width} and height is {dimensions?.height}.</div> ); } export default Component;
If you want to get the dimensions on window resizing, you'll need to define a listener as well:
jsximport React, { useEffect, useState } from 'react'; const Component = () => { const [dimensions, setDimensions] = useState(null); useEffect(() => { const getScreenDimensions = () => { setDimensions({ width: window.screen.width, height: window.screen.height }) } getScreenDimensions(); window.addEventListener('resize', getScreenDimensions); return () => window.removeEventListener('resize', getScreenDimensions); }, []); return( <div>Window width is {dimensions?.width} and height is {dimensions?.height}.</div> ); } export default Component;
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.