Search code examples
javascriptcssreactjsstyled-components

How to trigger animations using Styled-Components?


Currently, I use the following method to trigger an animation. I set the state to true and after some time, using setTimeout, I set it to false. Is there any way to do this without using setTimeout?

import React, { useState } from 'react';
import styled, { keyframes } from 'styled-components';

const growAnimation = keyframes`
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
`;

const StyledButton = styled.button`
  padding: 10px 20px;
  font-size: 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  animation: ${props => (props.animate ? `${growAnimation} 1s ease-in-out` : 'none')};
`;

const AnimatedButton = () => {
  const [animate, setAnimate] = useState(false);

  const handleClick = () => {
    setAnimate(true);
    setTimeout(() => {
      setAnimate(false);
    }, 1000);
  };

  return (
    <StyledButton animate={animate} onClick={handleClick}>
      Click me!
    </StyledButton>
  );
};

export default AnimatedButton;

Solution

  • By using animation-delay, animation-duration and animation-fill-mode: forwards; you can control the timing and number of times of play.

    But what if the user wants to replay the animation? If you use a CSS solution to stop the repeat of animation you won't have access to the state and replaying the animation wouldn't be possible.

    So using setTimeout is the proper way.