Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
React detect device when the page's width or height changes

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda