Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
How to add a classname in React Js?

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 :(

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda