Next.js: how can i handle window scroll event

Created on 25 Jan 2019  路  10Comments  路  Source: vercel/next.js

Hi. I worked on project with nextjs and i need to set scroll event handler for window. How can i do it ?

Most helpful comment

@Mracobes9

componentDidMount() {
        window.addEventListener('scroll', this.onScroll, false);
    }

    componentWillUnmount() {
        window.removeEventListener('scroll', this.onScroll, false);
    }

with Hooks

const handleScroll = () => {}
useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  });

All 10 comments

As in any React app, in componentDidMount you need to add the event listener to window and in componentWillUnmount you need to remove it.

Can you get example app ?

@sergiodxa no working

@Mracobes9

componentDidMount() {
        window.addEventListener('scroll', this.onScroll, false);
    }

    componentWillUnmount() {
        window.removeEventListener('scroll', this.onScroll, false);
    }

with Hooks

const handleScroll = () => {}
useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  });

const handleScroll = () => {}
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
});

This is working in my react project but does nothing in next js

Have you figured it out @pedroview ?

Have you figured it out @pedroview ?

I gave the solution that worked for me above

Hmm.. it's not working for me. I have to add the scroll event listener into the body instead for the work around.

Hmm.. it's not working for me. I have to add the scroll event listener into the body instead for the work around.

Same for me .. and document.documentElement.scrollTop is 0 :(

Hmm.. it's not working for me. I have to add the scroll event listener into the body instead for the work around.

Same for me .. and document.documentElement.scrollTop is 0 :(

I'm not sure if it's a bug or something, but it happened because I had the overflow-x: hidden in the body's style, after removing it, the window's scrolling event was back to work properly, that's kind of weird 馃槄

Was this page helpful?
0 / 5 - 0 ratings

Related issues

flybayer picture flybayer  路  3Comments

pie6k picture pie6k  路  3Comments

formula349 picture formula349  路  3Comments

timneutkens picture timneutkens  路  3Comments

knipferrc picture knipferrc  路  3Comments