简体   繁体   中英

Render different components based on screen size in Next.js

I'm trying to render render a component differently based on if the screen width < 768p.

If it is less than 768p, then load the hamburger menu. If not, load the entire menu.

Here's the code I use. The issue is, when the page first loads, I cannot observe the changes. But when I make the browser screen small and then increase it to it's original size; the effects take place.

I think it's because React is being rendered server-side. But still don't understand why it works by making the screen smaller and then bigger again.

import "twin.macro"
import { Global, css } from "@emotion/core"

import { useState, useEffect } from "react"

const Navbar = () => {
  const useWindowDimensions = () => {
    const hasWindow = typeof window !== "undefined"

    function getWindowDimensions() {
      const width = hasWindow ? window.innerWidth : null
      const height = hasWindow ? window.innerHeight : null
      return {
        width,
        height,
      }
    }

    const [windowDimensions, setWindowDimensions] = useState(
      getWindowDimensions()
    )

    useEffect(() => {
      if (hasWindow) {
        function handleResize() {
          setWindowDimensions(getWindowDimensions())
        }

        window.addEventListener("resize", handleResize)
        return () => window.removeEventListener("resize", handleResize)
      }
    }, [hasWindow])

    return windowDimensions
  }

  const { height, width } = useWindowDimensions()
  const breakpoint = 768

  return (
    <div>
      {width <= breakpoint ? (
        <div>
          <HamburgerMenu />
        </div>
      ) : (
        <div>
           <FullMenu />
        </div>
  )
}

export default Navbar

Is there a way I can force the Next.js app to apply the effects on the first render?

Next.js is universal, which means it executes code first server-side, then client-side. The window object is only present client-side

so in the first time it cannot access to window , so value of windowDimensions is null

when you resize you change the state make your app re-render, so it become client-side-rendering => you can access to window, then your code work

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