DEV Community

KiminLee
KiminLee

Posted on

Add an infinite scroll function to Telescope

getting started

So far, the Telescope generates more posts only when the "more post" button was click. Thanks to useSWRInfinite() and IntersectionObserver, the new posts can be rendered infinitely.

Implementation

First of all, we are going to grab a node, so we need useRef hook. Also, IntersectionObserver will be declared and assigned once the page is all loaded, so we need to have useEffect

import React, { useEffect, useRef } from 'react';
...
Enter fullscreen mode Exit fullscreen mode

Second, we need to find out which node should be the flag that the current post is the last post, and the new posts should rendered.

We can reuse the code from previous loadMoreButton.jsx button node.

    <Container>
      <Grid item xs={12} className={classes.content}>
        <Button ref={$buttonRef}>Load More Posts</Button>
      </Grid>
    </Container>
Enter fullscreen mode Exit fullscreen mode

This node will be the reference to indicate the post is the end of the current posts.

Third, we need to make it actually happen!

useEffect(() => {
    const options = {
      root: null,
      threshold: 1.0,
    };

    const observer = new IntersectionObserver(
      (entries) =>
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            onScroll();
          }
        }),
      options
    );
    observer.observe($buttonRef.current);

    return () => {
      observer.unobserve($buttonRef.current);
    };
  }, []);
Enter fullscreen mode Exit fullscreen mode

This will make the selected button node to be acted like a flag for check.

Top comments (0)