Search code examples
reactjsframer-motion

How to properly animate group of mapped items with framer-motion while array is changing?


I have an array like: base = [{title:'foo',items: [1,2]},{title:'bar',items:[1,2,3,4]}], then I map through this array with conditions:

 <motion.div variants={container} initial="hidden" animate="visible" exit={'hidden'}>
    {base[current].items.map(i =>
     <motion.div key={index} variants={item} >
         <div{i}</div>
     </motion.div>)}
</motion.div>

I need to animate all children, but now I only animate that children, which more in array... for example: (in that case) two children from first array in base is visible, if i change array (by toggle with a button for example) children 3 and 4 are appearing with animation, and hiding too, but children 1 and 2 changing without animation, how to resolve it ?

animation variants:

export const container = {
    hidden: { opacity: 1, scale: 0 },
    visible: {
        opacity: 1,
        scale: 1,
        transition: {
            delayChildren: 0.3,
            staggerChildren: 0.2
        }
    }
};

export const item = {
    hidden: { y: 20, opacity: 0 },
    visible: {
        y: 0,
        opacity: 1
    }
};

Solution

  • To resolve it we must to wrap our motion.div with AnimatePresence with attributes initial={false} mode={"wait"}, where mapped items will have different keys: for example key={i.title}