Issue with hamburger icon functionality after updating class name with UseState in React

As I design a navigation bar for a website, everything seems to be functioning smoothly, including the hamburger menu when resizing the screen. However, the issue arises when trying to click the hamburger menu while scrolling down the page.

By setting the initial state from 'false' to 'true,' it creates a reverse effect where the hamburger menu works only when scrolling but not when at the top of the page.

I have spent all day trying to troubleshoot this problem and find a solution without success. Any assistance in resolving this matter would be greatly appreciated.

Code for Navbar:

function Navbar2() {
  const [scrolled, setScrolled] = useState(false);

  const canvasRef = useRef();
  const navLinksRef = useRef();
  const liRefAbout = useRef();
  const liRefServices = useRef();
  const liRefGallery = useRef();
  const liRefTestimonials = useRef();
  const liRefContact = useRef();

  // toggle mobile menu on icon click
  useEffect(() => {
    const burger = canvasRef.current;
...
.......

CSS for Navbar:

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 8vh;
  background: transparent;
  transition: all 0.4s linear;

  position: sticky;
  position: -webkit-sticky;
  top: 0;
  z-index: 900;
}

.scrolled {
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(6px);
  width: 100%;
}

Answer №1

There are several optimizations that can be made in the code.

 useEffect(() => {
    const burger = canvasRef.current;
    const nav = navLinksRef.current;
    const aboutLink = liRefAbout.current;
    const servicesLink = liRefServices.current;
    const galleryLink = liRefGallery.current;
    const testimonialsLink = liRefTestimonials.current;
    const contactLink = liRefContact.current;

    burger.addEventListener('click', () => {
      nav.classList.toggle('nav-active');
      aboutLink.classList.toggle('list-about-active');
      servicesLink.classList.toggle('list-services-active');
      galleryLink.classList.toggle('list-gallery-active');
      testimonialsLink.classList.toggle('list-testimonials-active');
      contactLink.classList.toggle('list-contact-active');
      burger.classList.toggle('toggle');
    });
  }, [scrolled]);

Avoid adding event listeners every time the "scrolled" state changes. It is more efficient to add it only once when needed, as it doesn't depend on the "scrolled" state but rather on a button click event.

Also, there is no need to redeclare refs as constants since they will point to the same elements.

The second argument with an empty array triggers the useEffect hook only once:

useEffect(() => {
    const burger = canvasRef.current;
    const nav = navLinksRef.current;
    const aboutLink = liRefAbout.current;
    const servicesLink = liRefServices.current;
    const galleryLink = liRefGallery.current;
    const testimonialsLink = liRefTestimonials.current;
    const contactLink = liRefContact.current;

    burger.addEventListener('click', () => {
      nav.classList.toggle('nav-active');
      aboutLink.classList.toggle('list-about-active');
      servicesLink.classList.toggle('list-services-active');
      galleryLink.classList.toggle('list-gallery-active');
      testimonialsLink.classList.toggle('list-testimonials-active');
      contactLink.classList.toggle('list-contact-active');
      burger.classList.toggle('toggle');
    });
  }, []);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Excessive empty space appears on my mobile screen

Is there a solution to remove the white space issue that only occurs in mobile view? Here is an image of the problem: Untitled: https://i.sstatic.net/6WcGy.png I attempted using responsive instead of fluid, but it only resulted in the image being scaled ...

Intermittent occurrence of (404) Not Found error in the SpreadsheetsService.Query function

Using the Spreadsheet API, I frequently update various sheets. Occasionally, and without any pattern, the SpreadsheetsService.Query function returns a (404) Not Found error. This issue does not seem to be related to internet connectivity or server downti ...

When refreshing in React-Native, the Header and BottomTabNavigator display with increased height

I've been grappling with this issue for days now and haven't been able to find a solution. Any help is greatly appreciated. Whenever I reload the app, both the BottomTabBar and the Header experience an increase in height. Once the app has finishe ...

Position Bootstrap Modal in the center horizontally

I am working on an Angular project and struggling to center my Bootstrap 3 Modal horizontally on the screen. Despite trying various solutions like using text-align: center and align = "center", I have been unsuccessful. Can someone guide me on how to prope ...

Designing exquisite button navigation

Hey everyone, I'm currently working on creating a circular button navigation for my website. I want to have 4 buttons, each with a different color, and I want them to glow when the user hovers over them. So far, this is what I have in my HTML: HTML: ...

NodeJS throws an error when attempting to set headers after they have already been sent

I recently started learning NodeJS and I'm following a tutorial series for guidance. Link to the tutorial video While watching one of the videos, I encountered some errors after submitting a form. There are two specific doubts that I have been unabl ...

Using PHP variables in JavaScript is not compatible

Currently, I am facing an issue where PHP variables inside the javascript code are not being echoed. When I try to echo the variables outside of the javascript, everything works perfectly fine. After carefully reviewing my code multiple times, I still cann ...

Refreshing Form in Angular 2

When I remove a form control from my form, it causes the form to always be invalid. However, if I delete a character from another input field and then add the same character back in (to trigger a change event), the form becomes valid as expected. Is ther ...

PHP: implementing several forms on a single webpage

In my current situation, I need to display forms that resemble an Excel sheet with a submit button next to each row. When the submit button is clicked, the data is saved for that specific row, the row is disabled, and the focus automatically moves to the n ...

HTML sends a request prior to the loading of AngularJS

When including an HTTP request in the HTML, I encountered this issue: <img src="/api/profilepic/user/{{user.id}}"> The actual request URL is: Request URL:https://example.com/api/profilepic/user/%7B%7Buser.id%7D%7D As a result, the request keeps b ...

Methods for altering the color of a div using addEventListener

Why doesn't the color change when I click on the div with the class "round"? Also, how can I implement a color change onclick? var round = document.querySelector(".round"); round.addEventListener("click", function() { round.style.backgroundCol ...

Issue with border and color of Rounded Material Icons

I have integrated Material Icons Rounded into my website using the following code: <link href="https://fonts.googleapis.com/icon?family=Material+Icons|Material+Icons+Round" rel="stylesheet"> Additionally, I have a CSS rule for the rounded class: . ...

Issue with HTML5 Canvas y-axis dimensions

I am attempting to create a basic animated HTML canvas with a moving block controlled by WASD keys. I encountered an issue where drawing a 5x5 rectangle appeared to be 5x10 on the canvas. Upon inspecting my code and logging the position of the element, I d ...

What is the best way to choose CSS class attributes using Mootools and the getStyle()

Seeking to duplicate an object, I am trying to figure out how to retrieve class CSS attributes from Mootools. css: .card { width: 109px; height: 145px; } html: <div id="cards"> <div class="card" id="c0"> <div class="face fron ...

Utilizing Flexbox for a standalone section

I have a specific section in my HTML where I want to utilize flexboxes. The CSS provided is affecting all other rows and columns in my code. How can I ensure that this CSS only impacts the specific HTML section I have included here? Thank you! .row { ...

Accessing the API to retrieve an image when the 'a' tag is clicked

Currently, I am accessing the API to retrieve an image of a specific cat breed. When the API is called for the image, you receive a JSON object with the following URL: URL: "" I aim to display this image upon clicking on that specific breed. However, I a ...

The error message reads: "Attempting to call a class constructor Model without using the 'new' keyword in Sequelize 5 and Babel 7 results in a TypeError."

Currently working on a new project utilizing nodejs/express/sequelize. I'm using babel 7 to compile my ES6 code, and everything has been running smoothly with sequelize except for an issue that arises when attempting to use the removeHook method. When ...

Retrieve the highest value indexes from a three-dimensional array with JavaScript

In my dataset, I have an array structured like this: [34, 12, 56] [100,125,19] [30,50,69] The highest value in this array is 125, so the index [1,1] is returned. This means that 125, the highest value, can be found in row 1, column 1. To determine the i ...

Experimenting with React Component using React Router V6

I tried testing React Router with React Testing Library, but ran into issues as I am using react router V6. The Details component in my app depends on useParams() to retrieve part of the URL, making it essential for router testing. In an effort to make it ...

Having difficulty in transferring an array index as props to a different component

My goal is to create an app where users can add cards to an array and then switch the positions of specific cards with the one on their left or right. I have written a function to handle switching cards, but I am facing issues debugging it as the index of ...