javascriptreactjsreact-hooksmouseeventonscrolllistener

React Event handler failed to triggered in onScroll events


I am trying to listen to a scroll event. Here is the original code I converted.

document.addEventListener("scroll", function(){
const headerChange = document.querySelector("header");
if (window.scrollY > 0) {
headerChange.classList.add("scrolled");
} 
else {
headerChange.classList.remove("scrolled");
} 
})

while this is the way i converted it in my react code..

const [isScrolling, setIsScrolling] = useState(false);
    const navRef = useRef();


    const navScroll = () => {

        setIsScrolling(window.scrollY > 0 ? 
        navRef.current.classList.add("scrolled") 
        :  navRef.current.classList.remove("scrolled"));
        console.log(navScroll)
    }

return (
<nav
    ref={navRef} 
    onScroll={() => isScrolling}>

</nav>

)


the scroll event failed to triggered when the page was scrolled

Please, what could be the reason while the scroll function failed to triggered.


Solution

  • You need to listen to the page scroll, and not the nav scrolling, so you still need to use document.addEventListener('scroll', handleScroll);. Listening for DOM events is a side effect, that should be handled by useEffect. When the event is fired, you should update the state, and the state change should change the className - className={isScrolling ? 'scrolled' : ''.

    const Header = () => {
      const [isScrolling, setIsScrolling] = useState(false);
      
      useEffect(() => {
        const handleScroll = () => setIsScrolling(window.scrollY > 0);
        
        document.addEventListener('scroll', handleScroll);
        
        return () => { // cleanup
          document.removeEventListener('scroll', handleScroll);
        };
      }, []);
    
      return (
        <nav className={isScrolling ? 'scrolled' : ''}>
        ...
        </nav>
      )
    }