Detecting when user scrolls to bottom of div with React js

后端 未结 9 2211
悲哀的现实
悲哀的现实 2020-11-28 21:17

I have a website with different sections. I am using segment.io to track different actions on the page. How can I detect if a user has scrolled to the bottom of a div? I hav

9条回答
  •  旧时难觅i
    2020-11-28 22:03

    Here's a solution using React Hooks and ES6:

    import React, { useRef, useEffect } from 'react';
    
    const MyListComponent = () => {
      const listInnerRef = useRef();
    
      const onScroll = () => {
        if (listInnerRef.current) {
          const { scrollTop, scrollHeight, clientHeight } = listInnerRef.current;
          if (scrollTop + clientHeight === scrollHeight) {
            // TO SOMETHING HERE
            console.log('Reached bottom')
          }
        }
      };
    
      return (
        
    onScroll()} ref={listInnerRef}> {/* List items */}
    ); }; export default List;

提交回复
热议问题