Stackedo
Stackedo

Reputation: 923

How call a function from addEventListener in ReactJS?

I'm doing an infinite scroll in ReactJS but I'm in trouble!

After my component loads, I do this:

componentDidMount() {
    window.addEventListener('scroll', function() {
        var h = this.innerHeight;
        var j = document.documentElement.scrollHeight;
        var k = document.documentElement.scrollTop;
        if ((h + k) >= j - 150) {
            loadPhotos();
        }
    });
}

and, as a magic, I've "loadPhotos() is not defined". I can't use this.loadPhotos() because it refers to window (that hasn't loadPhotos()).

I initialize my loadPhotos() in the constructor() method:

this.loadPhotos = this.loadPhotos.bind(this);

My loadPhotos() is defined outside the constructor() method, I mean that is defined in the class body.

Someone can help me? Thank you guys!

SOLUTION

componentDidMount() {
    window.addEventListener('scroll', () => { // arrow boys
        var h = window.innerHeight;
        var j = document.documentElement.scrollHeight;
        var k = document.documentElement.scrollTop;
        if ((h + k) >= j - 150) {
            this.loadPhotos();
        }
    });
}

Upvotes: 3

Views: 2788

Answers (2)

Julian
Julian

Reputation: 1612

If you want to use your way, You would fix issue by using let _self = this.

Like this

componentDidMount() {
    let _self = this;
    window.addEventListener('scroll', function() {
        var h = window.innerHeight;
        var j = document.documentElement.scrollHeight;
        var k = document.documentElement.scrollTop;
        if ((h + k) >= j - 150) {
            _self.loadPhotos();
        }
    });
}

Upvotes: 3

Ori Drori
Ori Drori

Reputation: 191946

Use an arrow function as the callback, and this will refer to the component's instance.

Because the original this inside the callback referred to window, you also need to change this.innerHeight to window.innerHeight.

componentDidMount() {
    window.addEventListener('scroll', () => { // arrow function
        var h = window.innerHeight;
        var j = document.documentElement.scrollHeight;
        var k = document.documentElement.scrollTop;
        if ((h + k) >= j - 150) {
            this.loadPhotos(); // now you can use this
        }
    });
}

Upvotes: 7

Related Questions