'hi all am creating responsive navbar in react, when i clicked on toggle button i have to click twice to open it. How to open it by clicking one time

here's my react code. The navbar is working fine but when it is on mobile screen devices I have to click twice to open the burger menu. Can anyone help me with how to do it by only clicking one time?

export const Navbar = () => {

  const clicked = () =>{
    const burger = document.getElementById('burger');
    const ul = document.querySelector('nav ul');

    burger.addEventListener('click', () => {
      burger.classList.toggle('show-x');
      ul.classList.toggle('show');
    });
  }  
  
  return (
    <nav>
    <p>Learned.</p>
    <button onClick={clicked} id="burger" className="burger" >
      <div className="bar"></div>
      <div className="bar"></div>
    </button>
    <ul>
      <a href="#">Study</a>
      <li><a href="#">About Us</a></li>
      <li><a href="#">Addmission</a></li>
      <li><a href="#">Pages</a></li>
      <li><a href="#">News</a></li>
      <li><a href="#">Contact</a></li>
      <button className="apply">Apply Now</button>
    </ul>
  </nav>
  )
}


Solution 1:[1]

Change your code to something like this:

import {useRef} from 'react';
export const Navbar = () => {
  const burger = useRef();
  const clicked = () =>{
    const ul = document.querySelector('nav ul');
    burger.classList.toggle('show-x');
    ul.classList.toggle('show');
  }  
  
  return (
    <nav>
    <p>Learned.</p>
    <button onClick={clicked} ref={burger} className="burger" >
      <div className="bar"></div>
      <div className="bar"></div>
    </button>
    <ul>
      <a href="#">Study</a>
      <li><a href="#">About Us</a></li>
      <li><a href="#">Addmission</a></li>
      <li><a href="#">Pages</a></li>
      <li><a href="#">News</a></li>
      <li><a href="#">Contact</a></li>
      <button className="apply">Apply Now</button>
    </ul>
  </nav>
  )
}

I hope this would work for you. But I encourage you to improve your skills

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NatiG