#window.scrollY error typescript

1 messages · Page 1 of 1 (latest)

worldly lily
#

I'm trying to get the position of the webpage and use it as a condition to run some command if the condition is met.

```const getScroll = () => {
    const check = window.scrollY; // If I set the type here to HTMLElement the condition below here becomes invalid because check can't be compared to a number.
    if (check >= 100) {
        setScroll(true);
    } else {
        setScroll(false);
    }
};
window.addEventListener("scroll", getScroll);```
quiet heron
#

if I had to guess, this is a nextjs project

#

when your component gets rendered server side it doesn't have access to a window object

#

your code runs both on the client and the server in many cases

hollow rivet
#
  • if using nextjs 13+ and the app/ directory, have to add "use client"; at the top of the file to turn the component into a client-side-only component, window will then be defined
  • if using nextjs <13 or the pages/ directory, have to add a check before accessing window, to see if it's defined or not, to see if the component is running in the client or in the server
quiet heron
#

basically you either need to check for window, ensure that all your attempts to use window are within something like a useEffect, or use the new experimental "use client" guff

worldly lily
#

Oh

#

Thanks

hollow rivet
#

!resolved