You can detect the screen resolution using JavaScript within a React component. Here’s how you can achieve this:
import React, { useState, useEffect } from 'react';
function ScreenResolutionDetector() {
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 Resolution:</p>
<p>Width: {screenWidth}px</p>
<p>Height: {screenHeight}px</p>
</div>
);
}
export default ScreenResolutionDetector;
In this example, the ScreenResolutionDetector
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 resolution in pixels.
Keep in mind that this approach provides the current screen dimensions, but not the actual screen resolution in DPI (dots per inch). If you need to determine the DPI or handle responsive design based on different screen sizes, you might need additional techniques and libraries.
Also, be aware 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.