DEV Community

Austin Labador
Austin Labador

Posted on

Taking a Bite out of Hamburger Menus in React

Introduction

Hamburger menus are a common yet important part of an application's user interface that helps with navigation. They make navigation cleaner, provide top-level access, and are a very familiar icon to many users. In this article, I explore my process in creating a hamburger menu, and the hiccups along the way.

The Problem

I wanted to create a nav menu that shows when you click on a hamburger menu icon. When the menu shows, you should be able to click on those links and navigate to those menus, with the nav menu closing automatically. Additionally, you should be able to exit out of the menu when you click outside of it.

The Process

I started off with just an onClick. So you can open up a menu, but you can only close the menu when clicking the hamburger icon again. If you click outside, the menu stays there. This is fine, but not the greatest for UX.

I did some research and these were some of the resources that helped me most.

Focusing on Dynamically Added Element

Adding Hamburger Menu

ForwardRef

This was what I found worked the best for me.

Implementation

  • Click on nav button, handleClick to change state.
  • I set up a useEffect hook that runs every time the value of toggleNav(state) is changed.
  • Create a useRef hook to reference child component with forwardRef, which will be focused.
  • Since nav menu is conditionally rendered (when hamburger is clicked), setTimeout to focus on the newly rendered menu (child component).
  • Set up an event listener to
  • check if nav menu (toggleNav) is true,
  • if useRef current has a value,
  • and if the value of the currently clicked target (e.target), taken from the event listener, is not equal to useRef current.
  • If all the above conditions are fulfilled, then setToggleNav to false. This will make the nav bar close when you click anywhere that is outside of the ref.
  • Then remove the side effect (event listener) at the end of useEffect.

Resolving Final Issues

After trying a few different combinations of things, I was finally able to get my navbar to work. When I clicked outside of the menu, it would close. But now, when I clicked on the hamburger menu, it would stay open, or rather reopen!

At first I tried changing the conditions to the event listener, but that didn't give any good results. I ended up going with a CSS solution, preventing the user from clicking the hamburger menu icon again by hiding it.

Now that gave a different result, because the menu was a child component of the hamburger menu. So I added a class that would reduce the height and width of the component to 0 on click. This was what worked the best.


What I thought would be a simple task turned out to be a little more complicated. But, I was able to learn and get practice with useRef, a hook I was not very familiar with!

Top comments (0)