Search code examples
javascriptframer-motion

AnimatePresence and exit animation won't fire


I'm trying to make an animated countdown clock using framer motion.

I understand that any child of <AnimatePresence/> with a unique key should animate into and out of the parent. However, I just can't get the exit to work. Is it the way I'm injecting/replacing the spans?

<AnimatePresence>
  <div>
    {timeString.split("").map((val, i) => (
      <motion.span
        key={val + i}
        initial={{ y: 50, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        exit={{ y: -50, opacity: 0 }} <--- this doesn't seem to work
        transition={{
          x: { duration: 1, type: "spring", stiffness: 300, damping: 30 },
          opacity: { duration: 0.5 }
        }}
      >
        {val}
      </motion.span>
    ))}
  </div>
</AnimatePresence>

Codesandbox WIP

Documentation

EDIT: to clarify, i'm trying to get the numbers to enter from the bottom and leave via the top. Currently, they only enter from the bottom and there is no exit animation.


Solution

  • After some experimenting, I realized it's because there's a h1 tag inside of <AnimatePresence>. It isn't mentioned in the docs but it looks like <AnimatePresence> looks for specific child components. Adding in elements like span or div without using the <motion> component bugs it out.

    There are still imperfections to get exit looking perfect, but I've added a Codesandbox link that should unblock you.

    Codesandbox here

    P.S. framer-motion is a neat library thanks for sharing! Never knew it existed.