Exit Animations

Drag the square

1import { motion, useSpring, useMotionValue, useTransform } from 'motion/react'
2
3function AnimatingSquare() {
4  const x = useMotionValue(0)
5  const scalex = useTransform(x, [-100, 0, 100], [1, 1, 1.5])
6  const scale = useSpring(scalex)
7  const borderRadius = useTransform(x, [-100, 0, 100], ['50%', '0%', '50%'])
8  const backgroundColor = useTransform(
9    x,
10    [-100, 0, 100],
11    ['#4335a0', '#0f5878', '#9d4108']
12  )
13  return (
14    <div className="flex items-center justify-center">
15      <motion.div
16        style={{ x, scale, borderRadius, backgroundColor }}
17        className="w-32 h-32 bg-[#4335a0] rounded-md flex"
18        drag="x"
19        dragConstraints={{ left: 0, right: 0 }}
20      ></motion.div>
21    </div>
22  )
23}
24
25export default AnimatingSquare
26

Using Animate Presence

1
2import { useState } from 'react'
3import { motion, AnimatePresence } from 'motion/react'
4
5function ExitingSquare() {
6  const [isVisible, setIsVisible] = useState(true)
7
8  return (
9    <div className="flex  flex-col items-center justify-center space-y-4">
10      <button
11        onClick={() => setIsVisible(!isVisible)}
12        className="px-4 py-2 text-black font-semibold bg-yellow rounded hover:bg-yellow/80 transition-colors"
13      >
14        {isVisible ? 'Hide' : 'Show'} Square
15      </button>
16      <div className="min-h-60">
17        <AnimatePresence>
18          {isVisible && (
19            <motion.div
20              initial={{ opacity: 0, scale: 0, rotate: -180 }}
21              animate={{ opacity: 1, scale: 1, rotate: 0 }}
22              exit={{ opacity: 0, scale: 0, rotate: 180 }}
23              transition={{
24                type: 'spring',
25                stiffness: 260,
26                damping: 20,
27              }}
28              style={{
29                width: 128,
30                height: 128,
31                backgroundColor: '#4335a0',
32                borderRadius: 16,
33              }}
34              whileHover={{ scale: 1.1 }}
35              whileTap={{ scale: 0.9 }}
36            />
37          )}
38        </AnimatePresence>
39      </div>
40    </div>
41  )
42}
43export default ExitingSquare
44