To get the size of the screen in a React component, you can use the window.innerWidth
and window.innerHeight
properties. Here’s how you can do it:
import React, { useState, useEffect } from 'react';
function ScreenSize() {
const [screenWidth, setScreenWidth] = useState(window.innerWidth);
const [screenHeight, setScreenHeight] = useState(window.innerHeight);
useEffect(() => {
const handleResize = () => {
setScreenWidth(window.innerWidth);
setScreenHeight(window.innerHeight);
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return (
<div>
<p>Screen Width: {screenWidth}px</p>
<p>Screen Height: {screenHeight}px</p>
</div>
);
}
export default ScreenSize;
In this example, the ScreenSize
component uses the useState
and useEffect
hooks to track the screen width and height. The useEffect
hook listens for the resize
event on the window
object and updates the state with the current screen width and height when the window is resized.
The component then displays the current screen width and height in pixels.
Keep in mind that using the resize
event to track screen size changes can be resource-intensive. Consider using debouncing or throttling techniques to optimize the event handling, especially if your application needs to handle frequent resizing events.