Framer-motion: onAnimation callbacks not called on child elements

Viewed 1361

I have an animation setup like

<motion.div exit={{ opacity: 0}} initial="init" animate="loaded">
  <motion.div
    variants={variants}
    onAnimationStart={onAnimationStart}
    onAnimationComplete={onAnimationComplete}
  >
      Child element
  </motion.div>
  ...
</motion.div>

However, the child elements' onAnimation callbacks don't run unless I duplicate initial="init" animate="loaded" in the child elements like

<motion.div exit={{ opacity: 0}} initial="init" animate="loaded">
  <motion.div
    variants={variants}
    onAnimationStart={onAnimationStart}
    onAnimationComplete={onAnimationComplete}
    initial="init"
    animate="loaded"
  >
      Child element
  </motion.div>
  ...
</motion.div>

Is this intended behavior or am I doing something wrong?

1 Answers

It seems you're not understanding correctly the variants inheritance and functionality:

here it's an example of variants inheritance:
https://codesandbox.io/s/uotor?module=%2Fsrc%2FExample.tsx

in your example, for the animation callbacks and animation to work as expected, the variants prop is necessary in both motion.parent and motion.children

const parentVariants = { 
  init: { ...props } // parent animation styles
  loaded: { ...props } // parent animation styles
}
const childrenVariants = { 
  init: { ...props } // children animation styles
  loaded: { ...props } // children animation styles
}

// the variants must share the same "keys" in this case: "init" and "loaded"

<motion.div 
   exit={{ opacity: 0}} 
   initial="init" 
   animate="loaded" 
   variants={parentVariants}>
  <motion.div
    onAnimationStart={onAnimationStart}
    onAnimationComplete={onAnimationComplete}
    variants={childrenVariants}
  >
     Child element
  </motion.div>
</motion.div>

This SHOULD trigger the animations and callbacks as expected.

Related