duskload / react-device-detect

Detect device, and render view according to detected device type.
MIT License
2.81k stars 154 forks source link

isMobile doesn't work in Nexjs13 app #218

Open pj-alvarado10 opened 1 year ago

pj-alvarado10 commented 1 year ago

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.

DLParkin commented 1 year ago

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..

pj-alvarado10 commented 1 year ago

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

clintonmedbery commented 1 year ago

This worked for me: https://stackoverflow.com/a/77174374/3058839