I am trying to get window width and height at load and on resize; however, I get the following error. I do not see anything out of the ordinary with the html of the file.
Error: Hydration failed because the initial UI does not match what was rendered on the server.
Warning: Expected server HTML to contain a matching <div>
in <div>
.
See more info here: https://nextjs.org/docs/messages/react-hydration-error
Component Stack
div
div
NavHeader
./app/components/NavHeader.js (24:107)
body
html
NavHeader.js
'use client';
import Link from 'next/link'
import styles from 'styles/NavHeader.module.css'
import DensityMediumIcon from '@mui/icons-material/DensityMedium';
import { useState } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { auth } from "@/firebase";
export default function NavHeader() {
const [user, loading, error] = useAuthState(auth);
const [device, setDevice] = useState("");
if (typeof window !== "undefined") {
if (window.innerWidth < 1000) {
if (device !== "small") {
setDevice("small");
}
} else {
if (device !== "desktop") {
setDevice("desktop");
}
}
}
const clickHandler = () => {
const x = document.getElementById("menuMobile");
if (x.style.display === "flex") {
x.style.display = "none";
} else {
x.style.display = "flex";
}
}
if (typeof window !== "undefined") {
let w = window.innerWidth;
window.addEventListener("resize", function () {
let w = window.innerWidth;
if (w < 1000) {
setDevice("small");
} else {
setDevice("desktop");
}
})
}
return (
<div className={styles.headerContainer}>
<div className={styles.logo} />
{(device === "desktop") &&
<div id={"desktopMenu"} className={styles.desktopMenu}>
<Link href={"/"}>HOME</Link>
<Link href={"/about"}>ABOUT US</Link>
<Link href={"/electricity"}>ELECTRICITY</Link>
<Link href={"/pool-heating"}>POOL HEATING</Link>
<Link href={"/contact-us"}>CONTACT US</Link>
{user && <Link href={"/dashboard"} className={styles.signIn}>DASHBOARD</Link>}
{!user && <Link href={"/sign-in"} className={styles.signIn}>CUSTOMER LOGIN</Link>}
</div>
}
{(device === "small") &&
<div>
<DensityMediumIcon id={"menuIcon"} onClick={clickHandler} className={styles.expand} />
<div id={"menuMobile"} className={styles.menuMobile}>
<Link href={"/"} onClick={clickHandler}>HOME</Link>
<Link href={"/about"} onClick={clickHandler}>ABOUT US</Link>
<Link href={"/electricity"} onClick={clickHandler}>ELECTRICITY</Link>
<Link href={"/pool-heating"} onClick={clickHandler}>POOL HEATING</Link>
<Link href={"/contact-us"} onClick={clickHandler}>CONTACT US</Link>
{user && <Link href={"/dashboard"} onClick={clickHandler}>DASHBOARD</Link>}
{!user && <Link href={"/sign-in"} onClick={clickHandler}>CUSTOMER LOGIN</Link>}
</div>
</div>
}
</div>
)
}
I am using Next.js v14.1.0. Any help would be much appreciated.