skip to Main Content

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;

2

Answers


  1. Is there any way to do this without using setTimeout?

    You can set the animation fill-mode to forwards, so the animation will be triggered only once and will stay in the new state.

    `${growAnimation} 1s ease-in-out forwards`
                                 // ^^^^^^^^^
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search