loading...
Cover image for Burger Animation with React Hooks

Burger Animation with React Hooks

paulryan7 profile image Paul Ryan ・1 min read

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!!!!)

Posted on by:

paulryan7 profile

Paul Ryan

@paulryan7

Developer hailing from Ireland, love all things JS and starting to fall in love with SVGs!

Discussion

markdown guide