I need to have a global variable which tells me what device I am currently using, my team wants me to have mobile, tablet, desktop and mobile landscape. I didn't have any idea how to do that, but I started digging in google and found out this function:
const DeviceDetector = () => {
let hasTouchScreen = false;
if ("maxTouchPoints" in navigator) {
hasTouchScreen = navigator.maxTouchPoints > 0;
} else if ("msMaxTouchPoints" in navigator) {
hasTouchScreen = navigator.maxTouchPoints > 0;
} else {
const mQ = matchMedia("(pointer:coarse)");
if (mQ && mQ.media === "(pointer:coarse)") {
hasTouchScreen = !!mQ.matches;
} else if ("orientation" in window) {
hasTouchScreen = true; // deprecated, but good fallback
} else {
// Only as a last resort, fall back to user agent sniffing
const UA = navigator.userAgent;
hasTouchScreen =
/\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
/\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA);
}
}
if (hasTouchScreen) {
setDeviceType("Mobile");
} else {
setDeviceType("Desktop");
}
}
but the problems here are two, first: this function only detects mobile and desktop, but the bigger problem is: I need this function to fire whenever the width or height of the page changes, which I tried doing by adding it in this useEffect:
useEffect(() =>{
DeviceDetector();
console.log('changing device type', deviceType);
},[window.innerWidth, window.innerHeight, window.outerWidth, window.outerHeight])
For a moment it seemed its working fine, but when its firing its showing either always mobile or desktop depends on what you loaded the page with. I would be glad if some of you encountered the same problem and can face me in the right direction, is there a tool to make things easier, I read of react-device-detect but it seems that it also needs a page refresh to detect device changes. I tried a bunch of things regarding the landscape mobile but no luck.
CodePudding user response:
You could use a hook. Previously I have been using this to access the screen dimensions:
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;
}
You can map the dimensions to devices to get what you're looking for.