Search code examples
javascriptreactjsreact-hooksinfinite-scroll

JS scroll event is not trigerring inside React's useEffect


I want to add the infinite scrolling feature on my website, but I'm getting an issue with the scroll eventListener that is not triggering while I scroll the page.

useEffect(() => {
    window.addEventListener("scroll", handleInfiniteScrolling);
    console.log("Hello");
    return () => {
      window.removeEventListener("scroll", handleInfiniteScrolling);
    };
  }, []);
const handleInfiniteScrolling = async () => {
    try {
      console.log("Scroll Height", document.documentElement.scrollHeight);
      console.log("Inner Height", window.innerHeight);
      console.log("scrollTop", document.documentElement.scrollTop);
    } catch (err) {
      console.log(err);
    }
  };
return (
    <>
      <div
        className="results-page"
        style={{
          height: "100vh",
          overflow: 'scroll',
        }}
      >
        {data.map((item) => (
          <MainLayer props={item} key={item._id} />
        ))}
      </div>
    </>
  );

Solution

  • The div is the scroll container, and the content inside the div is scrolled. You need to add the event listener to the div using the onScroll event:

    const data = Array.from({ length: 100 }, () => ({ _id: crypto.randomUUID() }));
    
    const Demo = () => {  
      const handleInfiniteScrolling = e => {
        console.log(e.target.scrollTop)      
      };
    
      return (
        <div
          onScroll={handleInfiniteScrolling}
          className="results-page"
          style={{
            height: "100vh",
            overflow: 'scroll',
          }}
        >
          {data.map(item => (
            <div key={item._id}>{item._id}</div>
          ))}
        </div>
      );
    };
    
    ReactDOM
      .createRoot(root)
      .render(<Demo />);
    html, body {
      margin: 0;
    }
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    
    <div id="root"></div>