Home > Enterprise >  How to trigger framer motion animation onClick
How to trigger framer motion animation onClick

Time:12-19

I am applying a slide in animation using framer motion which slides in the User Card below on page render, but I want to trigger the animation on click of a button

Code below

const wrapperVariants = {
    hidden: { 
      opacity: 0, 
      x: '100vw' 
    },
    visible: { 
      opacity: 1, 
      x: 0,
      transition: { type: 'spring', delay: 0.1 }
    },
    exit: {
      x: "-100vh",
      transition: { ease: 'easeInOut' }
    }
  };

               <motion.div
                variants={wrapperVariants}
                initial="hidden"
                animate="visible"
                exit="exit"
                >
              <UserCard />
              </motion.div>

            <button onClick={() => {
              I want to Trigger the Animation on button click not just on render
            }}></button>

CodePudding user response:

You could do something like

const [clicked, setClicked] = useState(false)

            <motion.div
            variants={wrapperVariants}
            initial="hidden"
            animate= {clicked ? 'visible' : 'hidden'}
            exit="exit"
            >

<button onClick={() => setClicked(!clicked)}></button>

CodePudding user response:

You can use animation control hook in framer motion and for your case it would be sth like this :

 const wrapperVariants = {
    hidden: {
      opacity: 0,
      x: '100vw',
    },
    visible: {
      opacity: 1,
      x: 0,
      transition: { type: 'spring', delay: 0.1 },
    },
    exit: {
      x: '-100vh',
      transition: { ease: 'easeInOut' },
    },
  };

  const controls = useAnimationControls();

      <motion.div variants={wrapperVariants} initial="hidden" animate={controls} exit="exit">
        <UserCard />
      </motion.div>

      <button onClick={() => controls.start('visible')}></button>
  • Related