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.
I added
exit={{ opacity: 0 }}
to a child of<RenderModal/>
. The entering animation usinginitial
andanimate
worked as expected.
<AnimatePresence>
around modal-root element<div id="root"></div>
<AnimatePresence>
<div id="modal-root"></div>
</AnimatePresence>
Error: Target container requires a DOM element
<div id="modal-root">
<AnimatePresence></AnimatePresence>
</div>
const Modal = ({
title,
footer,
children,
}) => {
<AnimatePresence>
{isVisible
&& (
<RenderModal
title={title}
footer={footer}
hide={hide}
>
{children}
</RenderModal>
)}
</AnimatePresence>
};
return (
<>
<Button onClick={show}>Open Modal</Button>
<AnimatePresence>
<Modal {...args}></Modal>
</AnimatePresence>
<p>Lorem ipsum dolor sit amet...</p>
</>
);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.