Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!