I'm trying to add an onScroll
event on a table. This is what I've tried:
componentDidMount() { ReactDOM.findDOMNode(this.refs.table).addEventListener('scroll', this.listenScrollEvent); } componentWillUnmount() { ReactDOM.findDOMNode(this.refs.table).removeEventListener('scroll', this.listenScrollEvent); } listenScrollEvent() { console.log('Scroll event detected!'); } render() { return ( <table ref="table"> [...] </table> ) }
I tried console.log(ReactDOM.findDOMNode(this.refs.table))
and I'm getting the correct result but scroll event is never fired at all. I looked in here but still failed. Any help would be so much appreciated.
import * as React from "react"; import { useScrollBy } from "react-use-window-scroll"; const HookExample = () => { const scrollBy = useScrollBy(); return ( <div> {/* Hard scroll down by 200 pixels */} <button onClick={() => scrollBy(200, 0)}>Hard Scroll By 200</button> {/* Smooth scroll down by 200 pixels */} <button ...
To detect when a user scrolls to bottom of div with React, we can check if the sum of the scrollTop and clientHeight properties of a scrollable element is equal to the scrollHeight property of the same element. We call the useRef hook to create a ref and we assign the returned ref to the inner div, which is scrollable.
You need to bind this to the element in context.
render() { return ( <table ref="table" onScroll={this.listenScrollEvent.bind(this)}> [...] </table> ) }
You can use onScroll
attribute:
listenScrollEvent() { console.log('Scroll event detected!'); } render() { return ( <table onScroll={this.listenScrollEvent}> [...] </table> ) }
Here is an example: https://jsfiddle.net/81Lujabv/
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