react-device-detect
react-device-detect copied to clipboard
can't get react-device-detect to render based on device
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
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 !
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
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
}
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.
But in any case using the package you mentioned seems like a good alternative, thank you for the help