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?
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>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With