How to use animation multiple times in framer motion

Viewed 1158

Just like in the title, I'm trying to animate my component multiple times when clicking a button. Currently, animation only runs once and then it doesn't work anymore, how could I possibly implement that

here is an example of what I'm trying to do:

const controls = useAnimation();

    const handleClick = (e) => {
        controls.start({
            rotate: "360deg",
        });
    };

return(
<motion.button onClick={handleClick}>Button</motion.button>
<motion.div className="someRect" animate={controls}></motion.div>
)
1 Answers

To be honest, I've never worked with useAnimation controls so I have no idea what's going on here and how to come around this obstacle using your approach, but you may achieve what you are after with something like this.

  <button onClick={() => setRotate((prevState) => prevState + 360)}>
    Button
  </button>
  <motion.div
    className="someRect"
    animate={{
      rotate: rotate,
      transition: { duration: 3 }
    }}
    style={{ width: "100px", height: "100px", background: "red" }}
  >
  </motion.div>

I know that this solution is not optimal as the state is growing and growing with each click to possibly very substantial size which may cause problems at some point.

Check my solution in this CodeSanbox

Hope maybe someone will come up with a much more elegant solution which I'd appreciate seeing too.

Related