Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

framer motion exit animation not working (using react and animate presence)

it doesn't work. why?

goal: fire animation before component unmounts

example component:

 import React from "react";
 import { useState } from "react";
 import { AnimatePresence, motion } from "framer-motion";
 export default function NotExit() {
 const [show, toggle] = useState(true);
 const MyComponent = ({ isVisible }) => (
 <AnimatePresence>
  {isVisible && (
    <motion.div
      key="modal"
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
    />
  )}
</AnimatePresence>
)
return (
<div className="relative w-screen h-screen flex flex-col-reverse justify-center items-center">
  <button
    className="bg-purple-600 p-2 rounded"
    onClick={() => {
      toggle(!show);
    }}
  >
    show
  </button>
  {show && (
    <AnimatePresence>
      <motion.section
        initial={{ y: 100 }}
        animate={{ y: 0 }}
        exit={{ opacity: 1, transition: { duration: 1 } }}
        key="cock"
        className="w-44 h-44 bg-red-500 rounded-xl"
        transition={{ duration: 1 }}
       ></motion.section>
     </AnimatePresence>
    )}
 </div>
);

solutions tried:

  1. adding key prop,
  2. adding duration to exit prop if for some reason the animation happens but quickly so i don't notice it
  3. adding mode="wait" to AnimatePresence

I haven't really tried the switch location thingy mainly because i couldn't import it and i think routes replaced it

like image 478
ayman dev Avatar asked Jan 26 '26 04:01

ayman dev


1 Answers

The placement of the AnimatePresence component here is not correct:

  {show && (
    <AnimatePresence>
      <motion.section
       ...
       ></motion.section>
     </AnimatePresence>
    )}

You need to move it outside to wrap the animated component with its condition:

    <AnimatePresence>
      {show && (
        <motion.section
        ...
        ></motion.section>
      )}
    </AnimatePresence>
like image 190
khangnd Avatar answered Jan 28 '26 20:01

khangnd