Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add scroll event in react component

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.

like image 484
Lord Salforis Avatar asked Sep 05 '16 07:09

Lord Salforis


People also ask

How do you scroll through a window in React?

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 ...

How does React JS detect scrolling?

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.


2 Answers

You need to bind this to the element in context.

render() {     return (         <table ref="table" onScroll={this.listenScrollEvent.bind(this)}>            [...]         </table>     ) } 
like image 181
Harkirat Saluja Avatar answered Oct 12 '22 15:10

Harkirat Saluja


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/

like image 21
Anton Kulakov Avatar answered Oct 12 '22 15:10

Anton Kulakov