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

112
Visualizações
First click on Nav Menu Button Giving Error and working fine after that ReactJs

I am trying to make a hide/show navbar in ReactJS. But on the first click I am getting this error and its working fine after the first click.

  • Note: Its twice and i have no idea why

enter image description here

Here is my code and its only working (after first error) when

setMenu(!menu);

is before

nav.classList.toggle("nav-open");

otherwise the error just keeps coming.

export default function Navbar() {
  const [menu, setMenu] = useState(true);
  const nav = document.querySelector("nav");

  const openNav = () => {
    setMenu(!menu);
    nav.classList.toggle("nav-open");
  };

  return (
    <nav id="nav-wrapper">
      <header className="nav-header">
        <div
          className="arrow-btn"
          onClick={() => {
            openNav();
          }}
        >
          {menu ? (
            <Icon.HiChevronDoubleLeft size={20} className="arrows" />
          ) : (
            <Icon.HiChevronDoubleRight size={20} className="arrows" />
          )}
        </div>
        <img src={Profiledp} alt="." />
        <p className="name">Naman Pokhriyal</p>
      </header>
  </nav>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This isn't the right way of doing this in React in the first place. You're already using the menu state value to determine if the menu is open is not, so why not continue to use the menu state value to determine if the menu is open or not? Something like this:

const openNav = () => {
    setMenu(!menu);
};

return (
  <nav id="nav-wrapper" className={menu ? "nav-open" : ""}>
  // etc.
);

Basically any time you're trying to directly manipulate the DOM in React, take a step back and try to find a way to manage that via state instead. Direct DOM manipulation in React almost always leads to bugs unless you really know what you're doing under the hood in the framework.

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