How to add an animation on click using React

Let's assume that we want to animate a container after clicking a button using React.

To simplify the problem, we will animate the button itself:

javascript
import React, { useState } from 'react';

const AnimatedButton = () => {
    
    const [shake, setShake] = useState(false);
    
    const animate = () => {
        
        // Button begins to shake
        setShake(true);
        
        // Buttons stops to shake after 2 seconds
        setTimeout(() => setShake(false), 2000);
        
    }
    
    return(
        <button onClick = {animate} className = {shake ? `shake` : null}>Click me</button>
    );
    
}

export default AnimatedButton;

If the user clicks on the button, the button will have className = 'shake' for 2 seconds. After this interval, the button will have className = null and it will remain steady again.

Lastly, we will define the animation to shake the button in CSS (thanks to Joe Hastings):

CSS
button.shake{
    animation: shake 1s infinite;
}
@keyframes shake {
  0%  { transform: translate(2px, 1px)   rotate(0deg);  }
  10% { transform: translate(-1px, -2px) rotate(-2deg); }
  20% { transform: translate(-3px, 0px)  rotate(3deg);  }
  30% { transform: translate(0px, 2px)   rotate(0deg);  }
  40% { transform: translate(1px, -1px)  rotate(1deg);  }
  50% { transform: translate(-1px, 2px)  rotate(-1deg); }
  60% { transform: translate(-3px, 1px)  rotate(0deg);  }
  70% { transform: translate(2px, 1px)   rotate(-2deg); }
  80% { transform: translate(-1px, -1px) rotate(4deg);  }
  90% { transform: translate(2px, 2px)   rotate(0deg);  }
  100%{ transform: translate(1px, -2px)  rotate(-1deg); }
}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.