[SOLVED] First click on Nav Menu Button Giving Error and working fine after that ReactJs

Issue

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>

Solution

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.

Answered By – David

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.