Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Fri Mar 31 2023

Animated burger menu button in React

In this post, we will show how to create an animated burger button in React.

Final result will look something like this (sorry for bad quality)

burger-button

Prerequisites

Create BurgerMenu.tsx component

We want to have our component as dumb as possible, hence, we are providing it with the isOpen boolean value in the props to avoid any local state inside of the BurgerMenu component. So in this example, we are assuming that the state is handled outside of this component since this is purely an UI component.

import style from "./BurgerMenu.module.scss"; interface IBurgerMenuProps { isOpen: boolean; } export const BurgerMenu = (props: IBurgerMenuProps) => { const { isOpen } = props; return ( <div className={style.burgerContainer}> <i className={`${style.line} ${isOpen ? style.lineTopOpen : ""}`} /> <i className={`${style.line} ${isOpen ? style.lineMiddleOpen : ""}`} /> <i className={`${style.line} ${isOpen ? style.lineBottomOpen : ""}`} /> </div> ); };

Styling

Let's apply some css to it

.burgerContainer { display: flex; flex-direction: column; gap: 0.25rem; cursor: pointer; .line { width: 32px; height: 2px; background-color: #5f6368; margin: 0.08rem 0; transition: 0.4s; } .lineTopOpen { transform: translate(0, 6px) rotate(-45deg); } .lineMiddleOpen { opacity: 0; } .lineBottomOpen { transform: translate(0, -12px) rotate(45deg); } }

There we go. The trick that makes the animation smooth is the three bottom classes. lineTopOpen which rotates the top line downwards, lineMiddleOpen becomes invisible and lineBottomOpen rotates upwards so it creates a X with the top line basically. Change the values and play around and you will understand it better.

Consume it

In your, e.g Header component, it should look something like this:

import { useState } from "react"; import { BurgerMenu } from "components/burger-menu/BurgerMenu"; export const Header = () => { const [menuOpen, setMenuOpen] = useState(false); return ( <div onClick={() => setMenuOpen(!menuOpen)}> <BurgerMenu isOpen={menuOpen} /> </div> ); };

Outro

Cool. So, this was a super quick guide on how we can create a burger menu button with some nice animation. I hope you liked it, and as usual, if any feedback, don't hesitate to contact us here.

Thanks for reading!

signatureFri Mar 31 2023
See all our articles