0

I'm using next.js to create a static page that outputs in SSG mode.

I would like to use the react-device-detect library to determine the output component based on the screen size.
Since the page is created as SSG, even if the screen size is changed after accessing the page, the components will not be changed in real time.
Of course, if you change the screen size and reload it, it will be reflected, but I want to reflect it in real time.
If next.js is not used and only react is used, it will be rendered each time, so there was no problem. Is there a solution to this point?

Best regard.

The source is below.

import { isMobile, BrowserView, MobileView } from "react-device-detect";

const Header = ({ pathname }) => (
  <header>
    {isMobile ? "mobile header" : "header"}
    <BrowserView>normal</BrowserView>
    <MobileView>mobile</MobileView>
  </header>
);

export default Header;
juliomalves
  • 42,130
  • 20
  • 150
  • 146
kisetu
  • 157
  • 12
  • `react-device-detect` doesn't detect the screen size, it detects the device type based on the User-Agent. If you want to react to screen size changes look into solutions like these [Get viewport/window height in ReactJS](https://stackoverflow.com/questions/36862334/get-viewport-window-height-in-reactjs). – juliomalves Nov 15 '21 at 19:51
  • 1
    Thank you for the reference link. With this as a reference, I will approach it in a different way. – kisetu Nov 16 '21 at 00:35

1 Answers1

1

Nextjs is Server Side rendered Framework, by default it will render component in server side and paint the html directly on client side.

As per your use-case, you need to do client side rendering for header component, or any module which works in client/browsers.

import dynamic from 'next/dynamic'

const headerWithNoSSR = dynamic(
  () => import('../components/Header'),
  { ssr: false }
)

function Home() {
  return (
    <div>
      <headerWithNoSSR />
    </div>
  )
}

export default Home

Try this code whenever you are using header component, and then this will work. More you can read here

abhikumar22
  • 1,764
  • 2
  • 11
  • 24
  • Thanks for your comment. I didn't know the NoSSR mode. thank you for teaching me. I tried it, but the result was the same. Do you mean to judge the screen size yourself without using this library? – kisetu Nov 15 '21 at 08:35
  • 1
    you will not get screen size in nextjs as it is server side rendered pages, for that you need to import that login in client/browser side, as screen size logic is client/browser specific, so directly importing it will not work – abhikumar22 Nov 15 '21 at 08:42
  • Thanks for your comment. Certainly there is no screen on the server. I understand. I will try to find another approach. – kisetu Nov 16 '21 at 00:34