Kurtis Jin
Kurtis Jin

Reputation: 45

How to make scroll work from jquery to React js

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");
            }
        });
         
    }, []);
}

Upvotes: 1

Views: 570

Answers (1)

Drew Reese
Drew Reese

Reputation: 203408

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);
    };
  }, []);
}

Upvotes: 1

Related Questions