How To Create the Best Animated React Hamburger Menu

Oscar Bastos
3 min readNov 22, 2021

--

Using React, Styled-Components and Spring Animations

Creating a Hamburger Menu using React

Making a hamburger may be a simple task, but crafting a React hamburger menu component with a smooth animation and responsive design that adapts to any size and stroke width can be a bit more challenging.

Ingredients

  • React
  • Styled-Components
  • React-Spring Animations

Recipe

  1. Create a circle shape button container.
  2. Add three lines inside the circle
Circle container with 3 lines inside

Creating an Animated Hamburger Menu with React:

  1. Add an onClick event to the parent container to trigger the animation.
  2. Add styling animations to the 3 lines:
  • Top line: rotate 45 degrees.
  • Middle Line: change opacity to 0.
  • Bottom Line: rotate -45 degrees.

By following these steps, you’ll have a delicious, interactive hamburger menu component that looks something like this:

Oops! What is that?

Now tell me what is the trick of this recipe?

Just like many recipes in real life, there’s often a secret step that only the cook knows. The key to crafting a responsive hamburger menu that can handle any size and stroke width is to do some calculations to determine the offset on the Y-axis after rotation, ensuring that both lines intersect perfectly in the center.

How to calculate the offset of the lines?

After scouring through numerous source code samples on CodeSandbox and reading several blogs on Medium, I couldn’t find a clear and easy-to-follow explanation on how to accomplish this calculation. Some examples even had the height and width hard-coded, making it difficult to understand.

So after a bit of analysis I came to this calculation to determine how much to offset on the y axis after rotating the lines:

const offsetY = containerHeight/2-strokeWidth/2;

Now both lines intersect exactly at the center independently of the size or the stroke width

I’ve put together this handy example so you can take a closer look and fully grasp the process of creating this type of interactive component using spring animations in React.

Serve up an animated hamburger menu component that your users will love with this recipe.

--

--