3

Situation

I built a React Modal component using React Portals (see Docs above). Before unmounting the component when the close button is clicked, I want to run an exit animation with Framer Motion using AnimatePresence. Unfortunately, I can't make it work and need help.

Links

What I tried

I added exit={{ opacity: 0 }} to a child of <RenderModal/>. The entering animation using initial and animate worked as expected.

  1. Wrap <AnimatePresence> around modal-root element
<div id="root"></div>
<AnimatePresence>
  <div id="modal-root"></div>
</AnimatePresence>
  1. Wrap as child of modal-root

Error: Target container requires a DOM element

<div id="modal-root">
  <AnimatePresence></AnimatePresence>
</div>
  1. Wrap around the component element
const Modal = ({
    title,
    footer,
    children,
  }) => {
   <AnimatePresence>
    {isVisible
      && (
        <RenderModal
          title={title}
          footer={footer}
          hide={hide}
        >
          {children}
        </RenderModal>
      )}
    </AnimatePresence>
  };
  1. Wrap around the used Component
return (
  <>
    <Button onClick={show}>Open Modal</Button>
    <AnimatePresence>
      <Modal {...args}></Modal>
    </AnimatePresence>
    <p>Lorem ipsum dolor sit amet...</p>
  </>
);
visionInc
  • 137
  • 2
  • 10

1 Answers1

0

Did you remember to include a key prop for the conditionally rendered element? I don't see it in your code snippets.

From the docs:

Child motion components must each have a unique key prop so AnimatePresence can track their presence in the tree.

Cadin
  • 2,235
  • 1
  • 12
  • 18