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 withAnimatePresence).whileHover/whileTap: Easy interactive animations.
💻 Code Example
code
1import { motion, AnimatePresence } from 'framer-motion';23function AnimatedList({ items }) {4 return (5 <ul className="space-y-2">6 <AnimatePresence>7 {items.map(item => (8 <motion.li9 key={item.id}10 // 1. Enter animation11 initial={{ opacity: 0, x: -20 }}12 animate={{ opacity: 1, x: 0 }}13 // 2. Exit animation14 exit={{ opacity: 0, scale: 0.8 }}15 // 3. Hover effect16 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}2627// 4. Simple toggle animation28const SimpleToggle = () => {29 const [isOn, setIsOn] = useState(false);3031 return (32 <div33 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.div38 layout // Smoothly animate between two positions39 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
- Build a 'Fade-in' component that reveals its children when they mount.
- Create an 'Animated Modal' that slides in from the bottom.
- Implement a 'Staggered' list animation where items appear one after another.
- Experiment with
layoutIdto animate elements moving between two different components (e.g., a shared layout transition).
⚠️ Common Mistakes
Animating non-GPU accelerated properties (like
heightormargin) which causes layout shifts. Prefertransform(scale, x, y) andopacity.Forgetting to wrap
exitanimations in<AnimatePresence>.Adding too many animations, making the UI feel slow or distracting.
Not considering users who prefer 'Reduced Motion' (use the
useReducedMotionhook).
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for Animations with Framer Motion
Was this topic helpful?