Update style of a component onScroll in React.js

You should bind the listener in componentDidMount, that way it’s only created once. You should be able to store the style in state, the listener was probably the cause of performance issues.

Something like this:

componentDidMount: function() {
    window.addEventListener('scroll', this.handleScroll);
},

componentWillUnmount: function() {
    window.removeEventListener('scroll', this.handleScroll);
},

handleScroll: function(event) {
    let scrollTop = event.srcElement.body.scrollTop,
        itemTranslate = Math.min(0, scrollTop/3 - 60);

    this.setState({
      transform: itemTranslate
    });
},

Leave a Comment