2

why if i using onScroll react version 16 cannot fire how to make it work. because i want using onScroll than onWheel?.

import ReactDom from 'react-dom'

constructor(props) {
    super(props);
    this._fireOnScroll = this.fireOnScroll.bind(this);
}

fireOnScroll() {
    console.log('Fire!');
}

componentDidMount() {
    const elem = ReactDOM.findDOMNode(this.refs.elementToFire);
    elem.addEventListener('scroll', this._fireOnScroll, true);
}

componentWillUnmount() {
    const elem = ReactDOM.findDOMNode(this.refs.elementToFire);
    elem.removeEventListener('scroll', this._fireOnScroll);
}

render() {
    return (
        <div ref="elementToFire">
      <AnotherComponent imagesUrl={Array(100)}}>}
    </div>
</div>
    );
}
justunknown
  • 55
  • 1
  • 6
  • Please show your actual code. What you posted here isn't valid. ReactDom <-> ReactDOM and no class around the functions you showed. – Daniel Hilgarth Apr 23 '18 at 08:05

2 Answers2

3

Your div is empty. scroll only fires if actual scrolling did happen.
So, your div needs to be smaller than its content and needs to show scrollbars.

See this pen for a working example.

However, there is no reason for using a ref. Simply use onScroll:

<div style={{height: 75, width: 100, overflow:'scroll'}} onScroll={this.fireOnScroll}>

See this pen for a working example.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • in your code very simple and still didn't work for me. actualy i have more than 100 image to show and if iwant see image what i get in my body. so i need scroll but onScroll cannot fire. – justunknown Apr 23 '18 at 09:46
  • 1
    You need to show your actual code if my answer doesn't help you. My answer shows working code, see the links. – Daniel Hilgarth Apr 23 '18 at 09:47
  • In my situation, I had data to be fetched, so before it fetched `scroll-y` set already to null, and after it populated and scroll shows but it's not working/updating in DOM may be. Though in desktop browser it works without problem, but in mobile browser `onScroll` not firing. – Sabbir Sobhani May 30 '22 at 17:34
0

Your ref is not properly assigned to the div it should be <div ref = {this.elementToFire} > If not works then try

const elem = ReactDOM.findDOMNode(this.refs.elementToFire.current); Also from the code you have given O guess you missed to create a ref object also

this.elementToFire = React.createRef();

Hope it will work

Aniketh Saha
  • 843
  • 10
  • 22