skip to Main Content

I want to track it so that when they reached bottom of the screen, i will call a function to fetch more data.
I have an app.js where inside is Products / component wherein it fetches data.
Products / is wrapped by a div.gallery container

I already used Intersection Observer but still fails, but maybe i used it wrong.

3

Answers


  1. const container = document.getElementsByTagName(“body”);
    
    function loadImages(numImages = 10)
    {
       let i = 0;
       while(i < numImages)
       {
         fetch('https://dog.ceo/api/breeds/image/random')
         .then(response => response.json())
         .then(data => {
            const img =  document.createElement('img');
            img.src = `${data.message}`
            container.appendChild(img)
          })
          i++;
       }   
    }
    
    window.addEventListener('scroll', () => {
        if(window.scrollY + window.innerHeight >= document.documentElement.scrollHeight)
        { loadImages(); }
    })
    

    Credit: Educative.io

    Login or Signup to reply.
  2. You can use react-intersection-observer and you can implement it like this.

    import { useEffect } from "react";
    import { useInView } from "react-intersection-observer";
    
    const MainComponent = () => {
      const { ref, inView } = useInView();
    
      useEffect(() => {
         if (inView) { fetchMoreData() }
      }, [inView])
    
      return (
         <div className="container">
            <div>{renderYourListHere()}</div>
            <div ref={ref} />
         </div>
      )
    }
    
    Login or Signup to reply.
  3. You can use IntersectionObserver like this, Whenever the end element is visible it’ll trigger a callback. You can perform any action you want inside the callback.

    // Create list
    const listItems = Array(100).fill(0);
    const list = document.querySelector("#list");
    listItems.forEach((item, i) => {
      const li = document.createElement("li");
      li.innerText = "item " + i;
      list.appendChild(li);
    });
    
    
    // Add intersection Observer
    let options = {
      root: null,
      threshold: 1,
    };
    
    const callback = (entries) => {
      const isVisible = entries[0].isIntersecting;
      if (isVisible) {
        console.log('End Element is Visible =>');
      }
    };
    
    let observer = new IntersectionObserver(callback, options);
    observer.observe(document.querySelector("#end"));
    <div id="list"></div>
    <div id="end">END</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search