skip to Main Content
const nav1=document.querySelector('.navbar');
 window.addEventListener('scroll',
      function ()
         {
            if(window.scrollY>70)
             {
                nav1.classList.add('new_nav');
             }
            else if (window.scrollY < 69) 
             {
            nav1.classList.remove('new_nav');
         }
     }

Im trying this code in React App.js file, if i scroll down it shows error like "nav1 is NULL".It worked when it was a html,js file.

If i scroll the class file need to change.

2

Answers


  1. events are handled a bit differently in ReactJS.I’ll suggest you read through React docs as well ReactJS Docs

    import React, { useRef, useEffect } from "react";
    
    export default function App() {
      const navRef = useRef(null);
    
      useEffect(() => {
        const nav1 = navRef.current;
        const onScroll = (event) => {
          if (window.scrollY > 70) {
            nav1.classList.add("new_nav");
          } else if (window.scrollY < 69) {
            nav1.classList.remove("new_nav");
          }
        };
    
        window.addEventListener("scroll", onScroll);
    
        return () => {
          window.removeEventListener("scroll", onScroll);
        };
      }, []);
    
      return (
        <nav className="App" ref={navRef}>
          navigation
        </nav>
      );
    }
    

    I’ve attached a solution here solution

    Login or Signup to reply.
  2. Can you give us more Content from your React File or Function?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search