How to avoid Window is not defined error in React and Nodejs .Window is not defined errors in React and JavaScript .
Learn more about Reactjs www.learncoders.xyz
1. First solution: typeof
While you can’t use:
if (window !== undefined) { // Type your code here }
2. Second solution: the useEffect hook
import React, { useEffect } from "react"; export default function Student() { useEffect(function mount() { function onScroll() { console.log("scroll!"); } window.addEventListener("scroll", onScroll); return function unMount() { window.removeEventListener("scroll", onScroll); }; }); return null;
3. Third solution: dynamic loading
A different solution is to load your Student component
function onScroll() { console.log("scroll!"); } window.addEventListener("scroll", onScroll); export default function Scroll() { return null; }
These way you can avoid Window is not defined error in your ReactJS Application .
See our More Project