'Framer motion modal - Animate presence does not work

I am using modal with framer motion, the initial animation for the modal works fine, but on the exit it does not work at all. The modal disappears immediately for some reason.

This is where I am opening the modal:

const Agenda = () => {
  const [modalOpen, setModalOpen] = useState(false);

  const close = () => setModalOpen(false);
  const open = () => setModalOpen(true);
  return (
    <>
      <AnimatePresence
       initial={false}
       exitBeforeEnter={true}
       >
        {modalOpen && (
            <Modal modalOpen={modalOpen} handleClose={close}>
              <AgendaContent />
            </Modal>
        )}
     </AnimatePresence>        
    </>
   );
};

export default Agenda;

And here is the modal itself:

const newspaper = {
hidden: {
transform: "scale(0) rotate(720deg)",
opacity: 0,
transition: {
  delay: 0.3,
},
},
visible: {
transform: " scale(1) rotate(0deg)",
opacity: 1,
transition: {
  duration: 0.5,
},
},
exit: {
transform: "scale(0) rotate(-720deg)",
opacity: 0,
transition: {
  duration: 0.3,
},
},
};

const Modal = ({ handleClose, children }) => {
return (
<Backdrop onClick={handleClose}>
  <motion.div
    drag
    onClick={(e) => e.stopPropagation()}
    className="modal"
    variants={newspaper}
    initial="hidden"
    animate="visible"
    exit="exit"
  >
    <img
      className="close-icon"
      src={CloseIcon}
      alt="close"
      onClick={handleClose}
    />
    {children}
  </motion.div>
</Backdrop>
);
};

export default Modal;

I followed this tutorial. I am not sure what I am doing wrong here, I am using the AnimatePresence there, any idea what could be wrong?



Solution 1:[1]

From the AnimatePresence docs:

Note: Direct children must each have a unique key prop so AnimatePresence can track their presence in the tree.

It's frustratingly easy to forget even if you know about the requirement.

Something like this should work:

<AnimatePresence
   initial={false}
   exitBeforeEnter={true}
   >
    {modalOpen && (
        <Modal key="modal" modalOpen={modalOpen} handleClose={close}>
            <AgendaContent />
        </Modal>
    )}
</AnimatePresence> 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cadin