Animations with Framer Motion

0/3 in this phase0/36 across the roadmap

📖 Concept

Animations bring life to a UI. Framer Motion is the most popular animation library for React because it's declarative and powerful.

The motion component: Replace any standard HTML tag with its motion equivalent (e.g., <div /> becomes <motion.div />).

Key Props:

  • initial: The starting state of the element.
  • animate: The state the element should move to.
  • transition: How the animation should behave (duration, spring, ease).
  • exit: How the element should animate when it's removed from the DOM (used with AnimatePresence).
  • whileHover / whileTap: Easy interactive animations.

💻 Code Example

codeTap to expand ⛶
1import { motion, AnimatePresence } from 'framer-motion';
2
3function AnimatedList({ items }) {
4 return (
5 <ul className="space-y-2">
6 <AnimatePresence>
7 {items.map(item => (
8 <motion.li
9 key={item.id}
10 // 1. Enter animation
11 initial={{ opacity: 0, x: -20 }}
12 animate={{ opacity: 1, x: 0 }}
13 // 2. Exit animation
14 exit={{ opacity: 0, scale: 0.8 }}
15 // 3. Hover effect
16 whileHover={{ scale: 1.02 }}
17 className="p-3 bg-white shadow rounded flex justify-between"
18 >
19 {item.text}
20 </motion.li>
21 ))}
22 </AnimatePresence>
23 </ul>
24 );
25}
26
27// 4. Simple toggle animation
28const SimpleToggle = () => {
29 const [isOn, setIsOn] = useState(false);
30
31 return (
32 <div
33 className={`w-16 h-8 flex rounded-full p-1 cursor-pointer ${isOn ? 'bg-green-500' : 'bg-gray-300'}`}
34 onClick={() => setIsOn(!isOn)}
35 style={{ justifyContent: isOn ? 'flex-end' : 'flex-start' }}
36 >
37 <motion.div
38 layout // Smoothly animate between two positions
39 transition={{ type: "spring", stiffness: 700, damping: 30 }}
40 className="w-6 h-6 bg-white rounded-full shadow"
41 />
42 </div>
43 );
44};

🏋️ Practice Exercise

  1. Build a 'Fade-in' component that reveals its children when they mount.
  2. Create an 'Animated Modal' that slides in from the bottom.
  3. Implement a 'Staggered' list animation where items appear one after another.
  4. Experiment with layoutId to animate elements moving between two different components (e.g., a shared layout transition).

⚠️ Common Mistakes

  • Animating non-GPU accelerated properties (like height or margin) which causes layout shifts. Prefer transform (scale, x, y) and opacity.

  • Forgetting to wrap exit animations in <AnimatePresence>.

  • Adding too many animations, making the UI feel slow or distracting.

  • Not considering users who prefer 'Reduced Motion' (use the useReducedMotion hook).

💼 Interview Questions

🎤 Mock Interview

Practice a live interview for Animations with Framer Motion