LogRocket Blog

Creating an animated hamburger menu icon for React

thumbnail

Table of Contents


Installing the library

Before we learn how to create a custom hamburger menu icon in React, one way to add a hamburger button to our React project is by using a library. Let’s install the library:

Creating a (ta)stateful hamburger button

A basic implementation will look like this: We’ve used React’s Hook to manage the expanded and collapsed state of the hamburger: The Hamburger component from the library provides properties like and to control the state of the menu icon. Additionally, the component offers various other properties to customize the appearance and behavior of the animated hamburger menu icon, as shown below:

Adding toggling logic for interactive menu behavior

Let’s toggle the hamburger menu based on user interaction. In a parent component, we’ll pass the state properties, , and , to the component similar to the earlier implementation with the library:

Preventing keyframe animation on page load

When the page loads, the hamburger menu is initially in a closed state. Recall, in the hamburger wrapper, we conditionally apply the and classes like this: This means that on page load, the class is applied, triggering the keyframe animations defined in our CSS: To prevent these animations from running automatically when the page loads, we need to ensure they only occur due to user interaction. We’ll also apply a focus style using the pseudo-class when the hamburger icon receives focus through keyboard navigation:

Exposing hamburger menu state

Whether using the library or our custom component, we have a menu button design to maintain its state, indicating whether it is expanded or collapsed: Any component within the same file as the can adapt to changes in the hamburger menu’s state. Create a file in the folder and add the following code: This setup manages the current state of the hamburger menu (open or closed) and provides this context to any subscribing components. To ensure that these components have access to the context state, we will wrap them with the as follows: The can now control the global context state that other components can consume rather than using the local state: Also, the and components can subscribe to state updates and react accordingly to the toggle state. The component should be implemented as follows:


We applied CSS animations with keyframes to enhance the visual appeal. We also provided a solution for how components can subscribe to state updates using React context, allowing other components such as and to react to state changes.