Toggle Class based on scroll React JS

后端 未结 7 1978
醉话见心
醉话见心 2021-02-01 06:38

I\'m using bootstrap 4 nav bar and would like to change the background color after ig 400px down scroll down. I was looking at the react docs and found a onScroll but couldn\'t

7条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-01 07:34

    I have changed @PouyaAtaei answer a bit for my use case.

    import { useState, useEffect } from "react"
    
    // Added distance parameter to determine how much 
    // from the top tell return value is updated.
    // The name of the hook better reflects intended use.
    export const useHasScrolled = (distance = 10) => {
    
      // setting initial value to false
      const [scroll, setScroll] = useState(false)
    
      // running on mount
      useEffect(() => {
        const onScroll = () => {
        // Logic is false tell user reaches threshold, then true after.
          const scrollCheck = window.scrollY >= distance;
          if (scrollCheck !== scroll) {
            setScroll(scrollCheck)
          }
        }
    
        // setting the event handler from web API
        document.addEventListener("scroll", onScroll)
    
        // cleaning up from the web API
        return () => {
          document.removeEventListener("scroll", onScroll)
        }
    
      }, [scroll, setScroll])
    
      return scroll
    }
    

    Calling the hook:

    const component = () => {
      // calling our custom hook and optional distance agument.
      const scroll = useHasScrolled(250)
    }
    

提交回复
热议问题