Infinite Scroll with React Hook & Intersection Observer

In this post, we going to use the useIntersectionObserver hook that I create in

Easy Lazy Loading with React & Intersection Observer API
AnxinYang ・ Apr 18 ・ 3 min read

#react
#typ…


This content originally appeared on DEV Community and was authored by AnxinYang

In this post, we going to use the useIntersectionObserver hook that I create in

In short, this hook will check if the target element is in the viewport of a document or window.

Ok, let's start with a component that will load a picture:

function Component({ id }: { id: number }) {
  const [data, setData] = useState<any>({});
  useEffect(() => {
    fetch(`https://jsonplaceholder.typicode.com/photos/${id}`)
      .then((res) => res.json())
      .then((data) => {
        setData(data);
      });
  }, []);
  return (
    <div style={{ height: "600px" }}>
      <img src={data.url} alt="pic" />
    </div>
  );
}

then, we can use it inside the App.js:

const pageSize=5;
export default function App() {
  const [count, setCount] = useState(0);
  return (
    <div className="App">
      {(() => {
        const children = [];
        for (let i = 1; i <= count * pageSize; i++) {
          children.push(<Component key={i} id={i} />);
        }
        return children;
      })()}
    </div>
  );
}

Now, we add the hook, a component that can be used as trigger, and an useEffect that can increase the counter:

const pageSize = 5;
export default function App() {
  const [count, setCount] = useState(0);
  const ref = useRef(null);

  const isBottomVisible = useIntersectionObserver(
    ref,
    {
      threshold: 0 //trigger event as soon as the element is in the viewport.
    },
    false // don't remove the observer after intersected.
  );

  useEffect(() => {
    //load next page when bottom is visible
    isBottomVisible && setCount(count + 1);
  }, [isBottomVisible]);

  return (
    <div className="App">
      {(() => {
        const children = [];
        for (let i = 1; i <= count * pageSize; i++) {
          children.push(<Component key={i} id={i} />);
        }
        return children;
      })()}
      <div ref={ref} style={{ width: "100%", height: "20px" }}>
        Bottom
      </div>
    </div>
  );
}

Now we can test the code, here is a demo:

Thank you all!


This content originally appeared on DEV Community and was authored by AnxinYang


Print Share Comment Cite Upload Translate Updates
APA

AnxinYang | Sciencx (2021-04-27T00:06:20+00:00) Infinite Scroll with React Hook & Intersection Observer. Retrieved from https://www.scien.cx/2021/04/27/infinite-scroll-with-react-hook-intersection-observer/

MLA
" » Infinite Scroll with React Hook & Intersection Observer." AnxinYang | Sciencx - Tuesday April 27, 2021, https://www.scien.cx/2021/04/27/infinite-scroll-with-react-hook-intersection-observer/
HARVARD
AnxinYang | Sciencx Tuesday April 27, 2021 » Infinite Scroll with React Hook & Intersection Observer., viewed ,<https://www.scien.cx/2021/04/27/infinite-scroll-with-react-hook-intersection-observer/>
VANCOUVER
AnxinYang | Sciencx - » Infinite Scroll with React Hook & Intersection Observer. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/27/infinite-scroll-with-react-hook-intersection-observer/
CHICAGO
" » Infinite Scroll with React Hook & Intersection Observer." AnxinYang | Sciencx - Accessed . https://www.scien.cx/2021/04/27/infinite-scroll-with-react-hook-intersection-observer/
IEEE
" » Infinite Scroll with React Hook & Intersection Observer." AnxinYang | Sciencx [Online]. Available: https://www.scien.cx/2021/04/27/infinite-scroll-with-react-hook-intersection-observer/. [Accessed: ]
rf:citation
» Infinite Scroll with React Hook & Intersection Observer | AnxinYang | Sciencx | https://www.scien.cx/2021/04/27/infinite-scroll-with-react-hook-intersection-observer/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.