skip to Main Content

I’m getting the error that ‘window is not defined’. Kindly assist

    useEffect(() => {
        const handleScroll = () => {
            if(typeof window !== 'undefined') {
            // detect scroll

            setActive(window.scrollY > 100);
        };

        // add event listener

        window.addEventListener('scroll', handleScroll);

        // clear event listener

        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
}}, []);

Code Snippet

2

Answers


  1. Chosen as BEST ANSWER

    The issue was because the leaflet library was using SSR instead of client, resulting in the error 'window is not defined'. I solved this by importing dynamic from nextjs. Please see the below screenshot

    https://prnt.sc/RWuE55T6skuA


  2. According to the screenshot, the code snippet has nothing to do with the error. It is telling you that somewhere you’re importing leaflet which apparently accesses the window object.

    You should most likely dynamically import that module with next/dynamic with no SSR.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search