1

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; 
1

1 Answer 1

1

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]) 
Sign up to request clarification or add additional context in comments.

1 Comment

where shall I put it inside the file? could you show me?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.