react-device-detect icon indicating copy to clipboard operation
react-device-detect copied to clipboard

can't get react-device-detect to render based on device

Open cameronamini opened this issue 4 years ago • 5 comments

I'm trying to render my website differently based on whether it's being viewed on desktop or mobile. However, even though I'm using react-device-detect it is not working as intended. Even when viewing my website on mobile, I end up getting both the components meant to be rendered in MobileView as well as the components rendered in BrowserView.

I made a code sandbox to replicate the issue, and in the sandbox it only shows the BrowserView component even when I change the view to mobile.

Mobile Device: Android, Galaxy Note 8 Desktop: Acer Aspire 5

cameronamini avatar Aug 05 '21 07:08 cameronamini

in your code sandbox your code is:

{isMobile ? <Hero /> : <MobileHero />}

so if mobile is detected render the non-mobile view otherwise render the mobile-view .... hhmmm !

andrewlorenz avatar Aug 17 '21 20:08 andrewlorenz

in your code sandbox your code is:

{isMobile ? <Hero /> : <MobileHero />}

so if mobile is detected render the non-mobile view otherwise render the mobile-view .... hhmmm !

Oh yikes, must have been playing around with it and left it like that. I fixed it but I'm still getting the the error

cameronamini avatar Aug 28 '21 02:08 cameronamini

you are using isMobile - which checks the device type not the dimensions of the viewport. This package is called react-device-detect which is a very accurate name!

You can use css / media queries, or if you want to detect it in your code, I suggest you use the react-responsive package. This has a really cute hook called useMediaQuery which allows you to code media queries based on breakpoints, e.g.

import { useMediaQuery }        from 'react-responsive';

const MyComponent = () => {

  const isNarrow = useMediaQuery({ maxWidth: 600 });
  const isMedium = useMediaQuery({ minWidth: 601, maxWidth: 1200 });
  const isWide   = useMediaQuery({ minWidth: 1201 });

  // etc
}

andrewlorenz avatar Sep 20 '21 16:09 andrewlorenz

Hmm, we use it at my workplace and for our product it does seem to render differently based on screen size only. For example mobile view renders if I choose a smaller screen size in chrome inspector there.

cameronamini avatar Sep 20 '21 18:09 cameronamini

But in any case using the package you mentioned seems like a good alternative, thank you for the help

cameronamini avatar Sep 20 '21 18:09 cameronamini