3

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();
        }
    });
}

2 Answers 2

7

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
        }
    });
}
Sign up to request clarification or add additional context in comments.

2 Comments

Man, thank you for your reply! It solves but not at all. The var h goes to "undefined" and so my if doesn't work :S So stupid, I update my question with the solution, love you man!
@Stackedo - You're welcome :) No need to update the answer with the solution, just accept the answer.
3

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();
        }
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.