reactjsscrolladdclassremoveclass

React add/remove class onScroll in Stateless component


How to add a class to a component when this start scrolling and then remove it when stop it in a Stateless component.

This isn't working

import React from 'react'

let scrollClass = 'Feed';

function handleScroll(e) {
  scrollClass = 'Feed scrolling';
}

export default function Feed(){

  return (
    <div className={scrollClass} onScroll={(e) => handleScroll(e)}>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur arcu leo. 
    </div>
  )
}

Solution

  • For the component to react to the state change you should be using the component's state and to do so extend from the React.component baseclass. Also, as there is no such event as onStopScroll so you could set up a timer when the onScroll event occurs:

    import React from 'react'
    
    
    export default class Feed extends React.component {
      constructor(props) {
        super(props)
        this.state = { scrollClass: 'Feed' }
      }
    
      handleScroll(e) {
        this.setState({ scrollClass: 'Feed scrolling' })
        setTimeout(() => { this.setState({ scrollCLass: 'Feed' }) }, 100)
      }
    
      render() {
        let { scrollClass } = this.state
    
        return <div className={ scrollClass } onScroll={ this.handleScroll }>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur arcu leo. 
        </div>
      }
    }
    

    This is illustrative, I did not run this code. Notice that I removed the parenthesis around the <div> and simplified the onScroll method injection by removing an unnecessary arrow function since you do not need the event object.

    The logic behind this is that even if the setTimeout triggers the state change, every time you scroll the component's state is set again and react re-renders the elements with the new state (scrollClass: 'Feed scrolling') and the cycle goes on and on.