אלון ברנד
אלון ברנד

Reputation: 1

React infinite scrolling mechanism

I need to implement an infinite mechanism of scrolling in the react project, and when I reach the bottom of the page to add more images to my images array in the Gallery component.

the problem is that it happens only ones, only in the first scrolling to the bottom of the page.

adding an image of my functions: scrolling functions

thanks for helping!!

Upvotes: 0

Views: 135

Answers (2)

Jose Greinch
Jose Greinch

Reputation: 458

What you can do is create a custom hook for that infinite scroll behaviour. That way you can easily reuse the code for multiple places in your application. You have to think about input / output for that hook:

  • input:

    1. callback to fetch more items,
    1. element to be monitored for when it reaches the bottom for the callback
  • output

    1. if list is loading or not (so you can show the spinner)

You can rely on intersection observer to be doing the heavy lifting for you. It should be normally supported on modern browsers.

I recently created an article on the subject if you want to check it here that covers it in full detail

Upvotes: 0

سعيد
سعيد

Reputation: 1764

you should listen for scrool event in componentDidMount and only removeListner in componentDidMount , also I noticed your removing the listener in your track scrolling function isn't that just counterproductive ? try removing that line

Upvotes: 0

Related Questions