Transitions and variants
- React course
- Advanced
- Lesson 39/56
- 4 min
Learn to define component states with variants.
Transitions and motion
The transition prop defines how the animation happens. duration is the time, ease is the curve, delay is the wait, repeat is the loop count.
Example: transition={{ duration: 0.5, ease: 'easeOut', delay: 0.2, repeat: Infinity }} gives a 0.5 second, ease-out, 0.2 second delayed, infinite loop animation.
For motion animate={{ x: 100, y: -50 }} slides on the x and y axes. For rotation rotate: 360 is used.
Modal animation
Animating a modal as it opens and closes improves the user experience. AnimatePresence animates a component when it is added or removed.
The structure <AnimatePresence>{isOpen && <motion.div ... /></AnimatePresence> runs an enter animation when the modal opens and an exit animation when it closes.
The exit prop defines the state before the component leaves the DOM; this gives a smooth close animation.
Practice Write an animated modal
Complete the skeleton. Write an AnimatedModal component. Import motion and AnimatePresence from 'framer-motion'. Inside <AnimatePresence> render {true && <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.3 }}>Modal</motion.div>}. Add export default.
Starter code
import { motion, AnimatePresence } from 'framer-motion';
// Write AnimatedModal hereSample solution
import { motion, AnimatePresence } from 'framer-motion';
function AnimatedModal() {
return (
<AnimatePresence>
{true && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.3 }}
>
Modal
</motion.div>
)}
</AnimatePresence>
);
}
export default AnimatedModal;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which value gives infinite repeat?
- 0
- Infinity Correct answer
- 1
- true
Explanation: Infinity gives infinite repeat.
2 exit prop
<motion.div exit={{ opacity: ____ }} />
<motion.div exit={{ opacity: 0 }} />
Explanation: exit opacity 0 makes it disappear.
3 Transitions and variants: match the terms
| Term | Meaning |
|---|---|
AnimatePresence |
Wraps enter/leave |
exit |
Leave state |
duration |
Duration |
Infinity |
Infinite repeat |