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);
};
}}, []);
2
Answers
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
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 thewindow
object.You should most likely dynamically import that module with
next/dynamic
with no SSR.