Tristan Vermeesch
Tristan Vermeesch

Reputation: 89

addEventListeners and React not working as planned

I try to make a timeline that is dynamicaly loaded when scrolling. Due to this I need the scroll event, combined with React.

window.addEventListener("scroll", console.log('scroll'), true);

This should console log a scroll every time I scroll, but it just log it once, then nothing

EDIT:

If I use it in my real application now, with this code :

callbackFunc = () => {
        for (var i = 0; i < items.length; i++) {
            if (this.isElementInViewport(items[i])) {
                items[i].classList.add("in-view");
            }
        }
    }

componentDidMount() {
        window.addEventListener("load", function (event) { this.callbackFunc(); }, true);
        window.addEventListener("resize", function (event) { this.callbackFunc(); }, true);
        window.addEventListener("scroll", function (event) { this.callbackFunc(); }, true)
    }

It says callbackFunc is not a function

Upvotes: 2

Views: 4165

Answers (3)

Nick Parsons
Nick Parsons

Reputation: 50684

This isn't working because the event listener expects a function as it's second argument (or an object implementing the EventListner interface) which it will call when the "scroll" occurs. console.log is a function, but console.log("scroll") isn't a function, its a called function. And so the value you are technically putting as the second argument is undefined (as console.log("scroll") returns undefined).

const a = console.log("scroll");
console.log(a); // undefined (the value of your second arugment)

So, you need to wrap the console.log() in a function, so the function is called, which will then call your console.log() method. You can achieve this by using an ES6 arrow function:

window.addEventListener("scroll", _ => console.log('scroll'), true);

window.addEventListener("scroll", _ => console.log('scroll'), true);
body {
  height: 200vh;
}

As per your edit, the arrow function should solve your issue. Currently, the window is calling your event listener function, so this is referring to the window, not the context of your app. Using an arrow function should fix this (as an arrow function doesn't have it's own this).

Upvotes: 4

elraphty
elraphty

Reputation: 630

Try adding it in reactjs

 componentDidMount() lifecycle function

Upvotes: 0

vedsmith92
vedsmith92

Reputation: 599

Try this:

window.addEventListener("scroll", function(event) { console.log('scroll'); }, true);

Upvotes: 3

Related Questions