duskload/react-device-detect

isMobile doesn't work in Nexjs13 app

pj-alvarado10 opened this issue · 3 comments

I use isMobile but it doesn't work when I open the website in web browser from the mobile. I need change a redirection (skype: to desktop, tel: to mobile), but the library always redirect to skype, even from a mobile device.

My code in Nextjs13 app is:

    const getCallLink = () : string => {
        if(isMobile) {
            return 'tel:';
        }
        else {
            return 'skype:';
        }
    }

I tested in a Xiami Redmi Device from Google Chrome browser.

I had the same issue, was a little upsetting as I am porting over some react to nextjs and did not want to have to rewrite it just yet.

I ended up making a hook which seems to be working ok, it uses requestAnimationFrame before checking the isMobile which seems to give it enough time to load in and be ready for validation.

An alternative is a setTimeOut but that may be more flaky than this.

Anyway enough foo

import { useState, useEffect } from "react";
import { isMobile } from "react-device-detect";

export const useDelayedMobileDetection = (): boolean => {
  const [hideUntilValidated, setHideUntilValidated] = useState<boolean>(false);

  useEffect(() => {
    requestAnimationFrame(() => {
      if (!isMobile) {
        setHideUntilValidated(true);
      }
    });
  }, []);

  return hideUntilValidated;
};

usage
const shouldHaveLoaded = useDelayedMobileDetection();

Hope it helps or at least gives some ideas on it..

Thank you!!, It works for me, too!!!