OnScroll reaction not working

I am trying to add an onscroll event handler to a specific dom element. Take a look at this code:

class ScrollingApp extends React.Component { ... _handleScroll(ev) { console.log("Scrolling!"); } componentDidMount() { this.refs.list.addEventListener('scroll', this._handleScroll); } componentWillUnmount() { this.refs.list.removeEventListener('scroll', this._handleScroll); } render() { return ( <div ref="list"> { this.props.items.map( (item) => { return (<Item item={item} />); }) } </div> ); } } 

The code is pretty simple, and as you can see, I want to handle scrolling through the list of div #. When I ran this example, it does not work. So I tried to associate this._handleScroll with the render method directly, it does not work either.

 <div ref="list" onScroll={this._handleScroll.bind(this)> ... </div> 

So, I opened the chrome inspector by adding the onscroll event directly:

 document.getElementById('#list').addEventListener('scroll', ...); 

and it works! I do not know why this is happening. Is this a React error or something else? or am I missing something? Any device would be much appreciated.

+7
reactjs
source share
1 answer

The root of the problem is that this.refs.list is a React component, not a DOM node. To get the DOM element that has the addEventListener() method, you need to call ReactDOM.findDOMNode() :

 class ScrollingApp extends React.Component { _handleScroll(ev) { console.log("Scrolling!"); } componentDidMount() { const list = ReactDOM.findDOMNode(this.refs.list) list.addEventListener('scroll', this._handleScroll); } componentWillUnmount() { const list = ReactDOM.findDOMNode(this.refs.list) list.removeEventListener('scroll', this._handleScroll); } /* .... */ } 
+9
source share

All Articles