frontend
frontend

Reputation: 11

How to Load when scrolled to bottom

Hello im creating a movie app and everything is there except how do i put infinitescroll in my file? i want when scroll to bottom a new poster will appear.

import React, { useEffect, useState } from "react";
import MovieCard from '../Components/MovieCard'


function Home() {
  const url =
    "http://api.themoviedb.org/3/movie/popular?api_key=328c283cd27bd1877d9080ccb1604c91&release_dates.lte=2016-12-31&sort_by=release_date.desc&page=1";
  const [movies, setMovies] = useState({
    data: [],
    loading: false,
    error: false
  });

  useEffect(() => {
    fetch(url)
      .then((res) => res.json())
      .then((data) =>
        setMovies({ data: data.results, loading: false, error: false })
      );
  }, []);

  return  (  
    
    <>
      {movies.data.map((movie) => (
          <MovieCard 
            movie={movie}
          />
      ))} 

 
    </>

  )
};

export default Home;

Upvotes: 1

Views: 51

Answers (1)

Daniel
Daniel

Reputation: 1601

This is very simple and you can do it without any external libraries

  1. Add some element at the end of the page, for example empty div (or use any existing element)
  2. Add react reference to that element
  3. Add scroll event listener to the window, where you compare if user scrolled beyond that element.

This could look something like this:

  const refLastElement = useRef()

  const checkScrollEnd = useCallback(() => {
    if (window.pageYOffset + window.innerHeight >= refLastElement.current.offsetTop) {
      // add more elements
    }
  }, [/* something */])

  useEffect(() => {
    window.addEventListener('scroll', checkScrollEnd)
    return () => window.removeEventListener('scroll', checkScrollEnd)
  }, [checkScrollEnd])

Upvotes: 1

Related Questions