Detecting when user scrolls to bottom of div with React js

后端 未结 9 2160
悲哀的现实
悲哀的现实 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条回答
  • 2020-11-28 22:01

    We can also detect div's scroll end by using ref.

    import React, { Component } from 'react';
    import {withRouter} from 'react-router-dom';
    import styles from 'style.scss';
    
    class Gallery extends Component{ 
    
      paneDidMount = (node) => {    
        if(node) {      
          node.addEventListener("scroll", this.handleScroll.bind(this));      
        }
      }
    
      handleScroll = (event) => {    
        var node = event.target;
        const bottom = node.scrollHeight - node.scrollTop === node.clientHeight;
        if (bottom) {      
          console.log("BOTTOM REACHED:",bottom); 
        }    
      }
    
      render() {
        var that = this;        
        return(<div className={styles.gallery}>
          <div ref={that.paneDidMount} className={styles.galleryContainer}>
            ...
          </div>
    
        </div>);   
      }
    }
    
    export default withRouter(Gallery);
    
    0 讨论(0)
  • 2020-11-28 22:02

    I know this has already been answered but, I think another good solution is to use what's already available out in the open source community instead of DIY. React Waypoints is a library that exists to solve this very problem. (Though don't ask me why the this problem space of determining if a person scrolls past an HTML element is called "waypoints," haha)

    I think it's very well designed with its props contract and definitely encourage you to check it out.

    0 讨论(0)
  • 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 (
        <div className="list">
          <div className="list-inner" onScroll={() => onScroll()} ref={listInnerRef}>
            {/* List items */}
          </div>
        </div>
      );
    };
    
    export default List;
    
    0 讨论(0)
提交回复
热议问题