Exit Animations

Drag the square

import { motion, useSpring, useMotionValue, useTransform } from 'motion/react'

function AnimatingSquare() {
  const x = useMotionValue(0)
  const scalex = useTransform(x, [-100, 0, 100], [1, 1, 1.5])
  const scale = useSpring(scalex)
  const borderRadius = useTransform(x, [-100, 0, 100], ['50%', '0%', '50%'])
  const backgroundColor = useTransform(
    x,
    [-100, 0, 100],
    ['#4335a0', '#0f5878', '#9d4108']
  )
  return (
    <div className="flex items-center justify-center">
      <motion.div
        style={{ x, scale, borderRadius, backgroundColor }}
        className="w-32 h-32 bg-[#4335a0] rounded-md flex"
        drag="x"
        dragConstraints={{ left: 0, right: 0 }}
      ></motion.div>
    </div>
  )
}

export default AnimatingSquare

Using Animate Presence


import { useState } from 'react'
import { motion, AnimatePresence } from 'motion/react'

function ExitingSquare() {
  const [isVisible, setIsVisible] = useState(true)

  return (
    <div className="flex  flex-col items-center justify-center space-y-4">
      <button
        onClick={() => setIsVisible(!isVisible)}
        className="px-4 py-2 text-black font-semibold bg-yellow rounded hover:bg-yellow/80 transition-colors"
      >
        {isVisible ? 'Hide' : 'Show'} Square
      </button>
      <div className="min-h-60">
        <AnimatePresence>
          {isVisible && (
            <motion.div
              initial={{ opacity: 0, scale: 0, rotate: -180 }}
              animate={{ opacity: 1, scale: 1, rotate: 0 }}
              exit={{ opacity: 0, scale: 0, rotate: 180 }}
              transition={{
                type: 'spring',
                stiffness: 260,
                damping: 20,
              }}
              style={{
                width: 128,
                height: 128,
                backgroundColor: '#4335a0',
                borderRadius: 16,
              }}
              whileHover={{ scale: 1.1 }}
              whileTap={{ scale: 0.9 }}
            />
          )}
        </AnimatePresence>
      </div>
    </div>
  )
}
export default ExitingSquare