Ah, I see! You’re looking to detect if the device is mobile before the page loads. That’s a common requirement for responsive design. Let’s break this down:
1.
Server-side detection:
For server-side mobile detection that works with getStaticProps, you can use the user-agent header. However, since getStaticProps runs at build time, you’ll need a different approach.
2.
Client-side detection with minimal FOUC (Flash of Unstyled Content):
We can use a combination of a small inline script and CSS to achieve this. Here’s how:
Let’s create a custom _document.js file:
1import Document, { Html, Head, Main, NextScript } from 'next/document'
2
3class MyDocument extends Document {
4 render() {
5 return (
6 <Html>
7 <Head>
8 <script dangerouslySetInnerHTML={{
9 __html: `
10 (function() {
11 var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
12 document.documentElement.classList.add(isMobile ? 'mobile' : 'desktop');
13 })();
14 `
15 }} />
16 </Head>
17 <body>
18 <Main />
19 <NextScript />
20 </body>
21 </Html>
22 )
23 }
24}
25
26export default MyDocument
This script runs immediately and adds either a ‘mobile’ or ‘desktop’ class to the <html> element.
Now you can use CSS to style your page based on the device type:
1.mobile .some-element {
2 /* Mobile styles */
3}
4
5.desktop .some-element {
6 /* Desktop styles */
7}
This approach:
1.
Runs before the page content loads
2.
Doesn’t interfere with getStaticProps
4.
Works for both static and server-side rendered pages
Remember, this method uses user-agent detection, which isn’t 100% reliable but is generally good enough for most use cases. For more accurate results, you might want to combine this with CSS media queries for specific breakpoints.
Need any clarification on this approach, Amad?