1

I am trying to use scrollY to add and remove class using react. I have it working with jquery but can't seem to grasp how to convert it into React. Here is the before and after. I am lost on how to target .navbar that lives in Navbar.js in a different folder as well. Please help!

$(document).ready(function(){
        $(window).scroll(function(){
            // sticky navbar on scroll script
            if(this.scrollY > 20){
                $('.navbar').addClass("sticky");
            }else{
                $('.navbar').removeClass("sticky");
            }

import React, { Component, useEffect } from 'react';
import Animate from 'animate.css-react';
import Navbar from '../Navigation/Navbar'



export default function Scroll() {
    
    const[scroll, setScroll] = useState(false);
    useEffect(() => {
        
        window.addEventListener("scroll", () => {
            if(window.scrollY > 20) {
                $('.navbar').addClass("sticky");
            }else{
                $('.navbar').removeClass("sticky");
            }
        });
         
    }, []);
}

1 Answer 1

1

Ideally you would use a React ref attached to the navbar to get access to the underlying DOMNode, but sometimes this isn't possible, and in these situations you can use document.getElementById.

export default function Scroll() {
  ...

  useEffect(() => {
    const navBar = document.getElementById(".navbar");

    const scrollHandler = () => {
      if (window.scrollY > 20) {
        navBar?.addClass("sticky");
      } else {
        navBar?.removeClass("sticky");
      }
    }
        
    window.addEventListener("scroll", scrollHandler);
    
    // Return effect cleanup function to remove listener
    return () => {
      window.removeEventListener("scroll", scrollHandler);
    };
  }, []);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I see! That makes sense! I am going to give it a go! Thank you for teaching me!

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.