Search code examples
reactjsframer-motion

Reversing a variant animation in framer motion


I have an animation set in a variant that triggers on whileHover, but when I un-hover, the animation reverses in a way that is different than the transition settings I have set up.

Is there a way to have the animation reverse with the same transition settings and variant approach I have described?

Codesandbox Here.


Solution

  • Two things:

    1. If you want to use the same transition for all variants, you can move it out of the variant declaration and just add it to the motion component using the transition prop.
    const childVariants = {
      start: {
        scaleX: 1
      },
      end: {
        scaleX: -1,
        // no transition here
      }
    };
    
    <motion.div
      key={i}
      variants={childVariants}
      style={{
        width: "50px",
        height: "50px",
        borderRadius: "50%",
        backgroundColor: "red"
      }}
      // transition here will be used for everything
      transition={{
        type: "tween",
        ease: [0.22, 1, 0.36, 1],
        duration: 2
      }}
    />
    
    1. You want to set the animate prop to the variant (or values) to animate to after hover. initial sets the initial state of the component, but animate defines what to animate to (from initial or hover or whatever).

    In your case that looks like this:

    <motion.div
      animate={"start"}
      whileHover={"end"}
      transition={{ staggerChildren: 0.2 }}
      style={{ display: "inline-block" }}
    >
        {renderChildren}
    </motion.div>