How to use Framer Motion <AnimatePresence> and React Portals?

Viewed 3071

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>
  </>
);
2 Answers

Hello I think might be late. but I solve with this code


import { ReactNode } from "react";
import ReactDOM from "react-dom";
import { AnimatePresence } from "framer-motion";

interface ModalWrapperProps {
    children: ReactNode;
    isShowing: boolean;
}

const ModalWrapper = ({ children, isShowing }: ModalWrapperProps) =>
    ReactDOM.createPortal(
        <AnimatePresence exitBeforeEnter>
            {isShowing && children}
        </AnimatePresence>,
        document.body
    );

export default ModalWrapper;

I inspired below post

https://blog.logrocket.com/implementing-animated-toasts-in-react/

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.

Related