Search code examples
url-routingnext.js13adaptive-design

How to separate mobile version code from the code of desktop version in nextJS?


I am working in a project with NextJS and I have finished the desktop version, when it comes to the mobile version my client doesn't want the responsive layout of desktop version but he wants another pages which are completly diffrents. For exemple the content of home page in the desktopn version is not the same for mobile users.

So my questios are:

  1. How can I detect the useragent then return the specific page regarding to which device the user is using ?
  2. How should I structure the code ? should I create two 'src' folder, one for each version of code ?

Thanks in advance.


Solution

  • You can detect if a user from mobile device or desktop by using library "mobile-detect"

    // ------- Use the following code in your page folder -------
    import MobileDetect from 'mobile-detect';
    
    function checkIsMobile(context) {
      const md = new MobileDetect(context.req.headers["user-agent"]);
    
      return md.mobile() || md.tablet();
    }
    
    export const getServerSideProps = async context => {
      const isMobile = checkIsMobile(context);
    
      return {
        props: {
          isMobile
        }
      };
    };
    
    
    // ------- Create context for holding isMobile value -------
    import { createContext } from 'react';
    
    export const GlobalContext = createContext({
      isMobile: false
    });
    
    export const GlobalContextProvider = ({ children, initialValue }) => {
      return <GlobalContext.Provider value={initialValue}>
          {children}
        </GlobalContext.Provider>
    }
    
    // ------- _app file passing isMobile value to context -------
    function App(props) {
       const { Component, pageProps } = props;
    
    
      return <>
        <GlobalContextProvider initialValue={{
          isMobile: pageProps.isMobile,
          // you can pass here isAuth value
          // is user authorised or not by checking it in getServerSideProps function
        }}>
          <Component {...pageProps} />
        </GlobalContextProvider>
      </>
    }
    
    // ------- hook for get value from context -------
    import { useContext } from "react";
    import { GlobalContext } from "...";
    
    export const useIsMobile = () => {
      const value = useContext(GlobalContext);
      return value.isMobile;
    };
    
    // ------- Example component -------
    
    const TestComponent = () => {
      const isMobile = useIsMobile();
    
      return (
        <div>
          { isMobile ? 'Mobile version' : 'Desktop version' }
        </div>
      )
    }