Solving the error message "window is not defined" in Nextjs

Hey, I'm attempting to create a component similar to [this tutorial][1] in my NextJS app but I'm running into an error

ReferenceError: window is not defined

//Navbar.js
import styles from "../styles/Navbar.module.css";
export default function Navbar() {
  if (typeof window !== "undefined") {
    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 provide some guidance? I'm fairly new to using Node. [1]: https://www.w3schools.com/howto/howto_js_navbar_slide.asp

Answer №1

During server-side rendering, the window object is undefined. To address this issue, ensure that this function is placed inside a useEffect block, as useEffect does not execute during server-side rendering.

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
}
}, [])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for developing a JSON model or schema in Express.js?

Looking to create a JSON model or schema for storing form input data on a local JSON file, I have experience with MongoDB but want to keep it simple in this project by using a basic JSON file. Is there a way to structure the data similar to a Mongoose sche ...

error message indicating that a static file could not be found following deployment as it is not located within the root directory

When deploying my Next.js web app in a directory other than the root, such as '/next' instead of '/', the static files in the public folder cannot be found. This is because the requested URL is not http://example.com/next/a.png, but rat ...

Refreshing the browser causes Angular route to display raw JSON data

I have been working on a MEAN stack application and I have set up a proxy configuration for development purposes. Everything seems to be in order as I am able to successfully call an API from Angular/Node. However, the issue arises when I refresh the brows ...

Getting the canonical URL for dynamic pages in NextJS. How can it be done?

Previous to nextjs 9.4, I relied on the next-absolute-url package to provide the origin in getInitialProps. With Next.js 9.5 and the implementation of Automatic Optimization, using getServerSideProps and getStaticProps is preferred. Unfortunately, the nex ...

Navigating the complexities of Async/Await: Exploring the challenges of Async/Await

Utilizing async/await, I aim to showcase the data obtained from a readable stream prior to displaying the corresponding message. Below is my code snippet: var stream = async function (){ var myStream = fs.createReadStream(__dirname+"/someText ...

Encountering an issue: "You need to be signed in. Please log in using `npm login` and attempt again." appears when attempting to release with NP

After creating a classic JavaScript package and integrating NP to streamline the publishing process, I encountered an issue when running the NP command with npm run np. The error message displayed was: npm ERR! code ENEEDAUTH npm ERR! need auth This comman ...

What is the specific process that Express.js uses to manage errors?

Regarding the trivial matter, it is common knowledge that Express comes with a built-in default error handler that expects four arguments (err, req, res, next) to manage "synchronous exceptions" such as ReferenceError, TypeError, etc: UPDATE: The query at ...

Creating a redirect button using React Material UI and React Router

I've been exploring how to use Material-UI with React and I'm struggling to figure out the best way to redirect to other pages or components. After reading various articles on different methods of redirection using react-router-dom, I still have ...

The asynchronous method in a Mongoose schema does not pause for completion

Here is the code snippet that I am currently working on: const user = await User.findOne({ email }).select('+password'); console.log(' user value : ', user); const boolean = await user.comparePassword(password, user.password); console.l ...

Issue: nodebuffer is incompatible with this platform

Currently, I am attempting to utilize the Shpjs package in order to import a Shape file onto a Leaflet map. According to the Shpjs documentation: shpjs Below is the code snippet I am working with: const [geoData, setGeoData] = useState(null); //stat ...

Encountering issues with node-gyp rebuild installation on Ubuntu 20.04.2 LTS

Having trouble running a project in Visual Studio Code. Every time I try to run 'npm install,' I keep getting this npm-gyp error. I've made sure to update Node, npm, and Python to the latest versions, including installing Python 2.7, but not ...

Having trouble accessing my account due to authentication issues

Exploring the realms of next-auth and prisma is an exciting journey for me as a newcomer. As I ventured into integrating them for authentication on a website, everything seemed to function seamlessly in development mode. However, upon attempting to sign in ...

Why am I encountering a warning about dangerouslySetInnerHTML and receiving empty content in Next.js?

First and foremost, I am aware that nesting <p> tags is not recommended. I have developed a Next.js application wherein one of my components sets rich text HTML in the following manner: <Typography dangerouslySetInnerHTML={{ __ ...

Change attention between TextFields by pressing the Enter key

Is there a way to make pressing Enter on a MaterialUI TextField shift focus to the next field, similar to how the Tab key operates? <TextField label='Documento' name="document" autoComplete="document" autoFo ...

Is it possible to refactor this forwardRef so that it can be easily reused in a function?

Currently, I am in the process of transitioning my application to Material UI V4 and facing challenges with moving my react router Link components into forwardRef wrapped components when setting the 'to' prop programmatically. The code below doe ...

Can you explain the varying methods of importing material-ui components and how they differ from each other?

After delving into the documentation for material-ui and exploring various online resources, it appears that there are multiple methods for importing the same component: import TextField from 'material-ui/TextField'; // or import TextField from ...

Achieving synchronous function execution with a single click in React

In my current project, I am utilizing ReactJs and Redux. I have encountered a scenario where I need to trigger two functions sequentially with just one click on the mainfunc(). The second function should only execute after the first function has complete ...

Ensuring uniformity in simultaneous read actions within MongoDB

I have a Node.js API called /create/appointment that performs two operations: STEP 1: Checking for an active appointment in the database. STEP 2: Creating an appointment if it does not exist. There are three collections: doctors patients appointments ...

What is the method to select a singular value from an Autocomplete in Material UI?

I am currently working on an Autocomplete feature to add country calling codes in my project. However, I have encountered an issue where when selecting a code from the drop-down list, both the country name and its specific code are being displayed. My goal ...

Validate on startup in Next.js that essential environmental variables are defined

When initializing a pre-existing Next.js project, it's often overlooked to generate and set up the .env file (or .env.local or equivalent). It would be beneficial if, upon server startup, there could be a check to ensure that essential variables are n ...