Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get scroll position of component?

How could I get scroll position of a ReactJS component (-which is scrollable)? I suppose I have to add a scroll event listener to my component but I'm stuck there as I don't know how to add it to component - only to window. And also by which prop can I access the scroll position?

like image 346
Rok Avatar asked Oct 29 '25 12:10

Rok


1 Answers

The scroller can be accessed via the ref. You will want to make sure the css is set to overflow: scroll or overflow: auto to ensure you actually get a scrollable content.

class MyScroller extends React.Component {
  scroller = null
  
  componentDidMount = () => {
    if (this.scroller) {
      this.scroller.addEventListener('scroll', this.handleScroll.bind(this), false)
    }
  }
  
  componentWillUnmount = () => {
    if (this.scroller) {
      this.scroller.removeEventListener('scroll', this.handleScroll.bind(this), false)
    }
  }
  
  handleScroll = () => {
    if (this.scroller == null) return
    const { scrollHeight, scrollTop, clientHeight } = this.scroller
    const scroll = scrollHeight - scrollTop - clientHeight

    if (scroll > 0) {
      // We are not at the bottom of the scroll content
    }
    else if (scroll == 0){
      // We are at the bottom
    }
  }

  render = () => (
    <div ref={rf => this.scroller = rf} className={styles.myScrollingContainer}>
      <MyScrollingStuff />
    </div>
  )

}
like image 166
ageoff Avatar answered Nov 01 '25 02:11

ageoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!