11

I'm trying to add onscroll event handler to specific dom element. 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>
        );
    }
}

Code is quite simple, and as you can see, I want to handle div#list scrolling. When I was running this example, it isn't working. So I tried bind this._handleScroll on render method directly, it doesn't work either.

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

So i opened chrome inspector, adding onscroll event directly with:

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

and it is working! I don't know why this happens. Is this a bug of React or something? or did I missed something? Any device will very appreciated.

1
  • 1
    It's working for me (webpackbin.com/V1ECCW5Vb), scroll within the block and then click the "Log" button at top of page to see the logs. Commented Jun 15, 2016 at 9:40

1 Answer 1

10

The root of the problem is that this.refs.list is a React component, not a DOM node. To get the DOM element, which 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);
    }
    /* .... */
}
Sign up to request clarification or add additional context in comments.

1 Comment

findDOMNode is deprecated. Instead of setting your div ref to "list" you need to set it up using <div ref={node => this.list = node} and then your mount/unmount functions can access the variable directly, without having to find the node, this.list.addEventListener(...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.