0

Im trying to add a classname to the nav bar when the user scroll down. I did this:

var myNav = document.getElementById("nav");

window.onscroll = function() {
  "use strict";
  if (document.body.scrollTop >= 150 || document.documentElement.scrollTop >= 150) {
    myNav.classList.add("scroll");
  } else {
    myNav.classList.remove("scroll");
  }
};

But it gave me an error:

Cannot read properties of null (reading 'classList')

I don't know why :(

1 Answer 1

4

You're getting that error because no element with that id exists. Perhaps it doesn't exist yet, or perhaps it never exists. But either way, I recommend you avoid mixing react with direct manipulation of the dom. The react way to do this is to listen for the scroll in a useEffect, and then set state:

const NavBar = () => {
  const [scroll, setScroll] = useState(false);
  useEffect(() => {
    const handleScroll = () => {
      setScroll(document.body.scrollTop >= 150 || document.documentElement.scrollTop >= 150);
    }
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    }
  }, []);

  return (
    <div id="nav" className={scroll ? "scroll" : undefined}>

    </div>
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! It works perfect!

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.