简体   繁体   中英

How to detect mobile device with NextJS

There are many topics and SO questions. but I don't find the best solution to detect mobile device.

I have two components. the first component is only for desktop, the second component is only mobiles.

{isMobile? 
(<SecondComponent />) 
: 
(<FirstComponent />)
}

most solutions used getInitialProps function. but the Nextjs says:

Recommended: getStaticProps or getServerSideProps .

link

You use something like this:

export const isMobileDevice = () => /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

The simple way is to let the browser tell you with matchMedia :

let isMobile = window.matchMedia("(max-width: 600px)").matches;

I haven't tried this, but this post suggesest using req.device . So you could probably do something like this

export async function getServerSideProps(context) {
 
  return {
    props: {
      device: context.req.device,
    },
  }
}

Edit: You will need express-device installed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM