DEV Community

Cover image for Burger Animation with React Hooks
Paul Ryan
Paul Ryan

Posted on

Burger Animation with React Hooks

I was recently messing around in Codesandbox with a react app and wanted to animate a burger SVG but in order to do this, I needed to use refs which meant I had to change my functional component to be a class! I also needed to use the lifecycle method componentDidMount so it looked like I was all out of options.

But...maybe...this Hooks thing everyone is talking about will save me? Turns out it did.

Previously I had to create my refs in the constructor like so:

constructor(props){
  super(props)
  this.burgerRef = React.createRef()  
}

Now I could do:

const burgerRef = useRef(null);

Still I needed some way to detect when my component mounted, otherwise I would try to animate an undefined element which is not fun! useEffect comes to the rescue:

So instead of:

componentDidMount(){
    ....
}

I could just do:

useEffect(() => {
  ....
})

And voila! I could now do a nice animation without needing to change my component to be a class.

I simply discussed the theory here, all the code including the animation is on the following Codesandbox (Codesandbox is really great, I am a patreon and I think everyone should be, I don't get anything for saying this or promoting Codesandbox but I just love it!!!!)

Top comments (1)

Collapse
 
nishimotos93047 profile image
Nishimotoson Kirven

To create a burger animation using React Hooks, you can start by setting up a state variable to manage the open and closed states of the burger menu. Use the useState hook to toggle the menu when a button is clicked, which will trigger a CSS animation for a smooth transition. As the burger icon opens, you can display a dropdown with a jack in the box menu with prices that includes enticing items like the Jumbo Jack for $4.29, Chicken Sandwich for $5.19, and the classic Tacos for $1.39 each. Implement additional animations to enhance the user experience, making the menu visually appealing and engaging for users exploring the delicious options available.