简体   繁体   中英

how to animate below element's position smoothly when upper element is removed from DOM In framer Motion

Problem

Layout prop animates position change of the pink div when the App component is rendered or Re-rendered but when an element is removed from the DOM it doesn't cause App re-render hence when purple div is removed from DOM the pink div snaps to top instead of animating.

How to animate pink div when purple div is removed from DOM?

Click on toggle button to remove Purple Div

codeSandBox-- https://codesandbox.io/s/amazing-shirley-6e3oqi?file=/src/App.js

You mustn't unmount the element. You can use the hook useAnimationControls provided in the module and have more control on animations.

import { motion, useAnimationControls } from "framer-motion";

export default function App() {
  const controls = useAnimationControls()
  const controlsTwo = useAnimationControls()
  
  const animOne = async() => await controls.start({
    scale: 0,
    transition:{
      ease: "easeInOut",
      duration: 1,
    }
  })
  const animTwo = async() => await controlsTwo.start({
    y: -232,
    transition:{
      ease: "easeInOut",
      duration: 1,
    }
  })


  const toggle = () => {
    animOne()
    
    setTimeout(() => {
      animTwo()
    }, 300)
  }


  
  return (
    <div className="App">

      <button onClick={() => toggle()}>Toggle</button>
          <motion.div
            className="purple-div"
            initial={{ y: 10 }}
            animate={controls}
          >
            Press toggle btn & Look at Lower Div
          </motion.div>
      <motion.div
        layout
        className="pink-div"
        initial={{ y: -100 }}
        animate={controlsTwo}
      >
        Look At Me
      </motion.div>
    </div>
  );
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM