1

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

isherwood
  • 52,576
  • 15
  • 105
  • 143
S.M_Emamian
  • 16,079
  • 27
  • 115
  • 222

3 Answers3

1

You use something like this:

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

Abhishek Sharma
  • 2,030
  • 19
  • 31
0

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

let isMobile = window.matchMedia("(max-width: 600px)").matches;
samuei
  • 1,585
  • 1
  • 8
  • 22
0

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.

Baruch
  • 2,241
  • 1
  • 15
  • 26
  • 1
    You forgot to mention that you need the `express-device` middleware. Also, can express middleware work with NextJS? – Samathingamajig Jun 14 '21 at 19:11
  • @Samathingamajig sorry I didn't see the second part of your comment. Yea, you can have a custom server with express – Baruch Jun 14 '21 at 19:27