Robbi
Robbi

Reputation: 251

How to fix "window is not defined" in Nextjs

Hi was trying to create a component like [this][1] in NextJS app but it showing error ReferenceError: window is not defined

//Navbar,js
import styles from "../styles/Navbar.module.css";
export default function Navbar() {
  window.onscroll = function () {
    scrollFunction();
  };
  function scrollFunction() {
    if (
      document.body.scrollTop > 20 ||
      document.documentElement.scrollTop > 20
    ) {
      document.getElementById("navbar").style.top = "0";
    } else {
      document.getElementById("navbar").style.top = "-50px";
    }
  }
  return (
    <div id="navbar">
      <a href="#">Home</a>
      <a href="#">About</a>
      <a href="#">Blog</a>
      <a href="#">Contact</a>
    </div>
  );
}

Can anyone help? Am just started node [1]: https://www.w3schools.com/howto/howto_js_navbar_slide.asp

Upvotes: 0

Views: 1463

Answers (1)

lissettdm
lissettdm

Reputation: 13078

window is undefined on ssr. Put this function inside useEffect block, useEffect don't run during ssr.

useEffect(()=> {
 window.onscroll = function () {
    scrollFunction();
  };
  function scrollFunction() {
    if (
      document.body.scrollTop > 20 ||
      document.documentElement.scrollTop > 20
    ) {
      document.getElementById("navbar").style.top = "0";
    } else {
      document.getElementById("navbar").style.top = "-50px";
    }
  }
return ()=> {
 //remove the event listener
}
}, [])

Upvotes: 3

Related Questions