Summary - Framer Motion
- React course
- Advanced
- Lesson 40/56
- 5 min
Make a modal animate when it opens and closes.
Summary - Framer Motion
In this group you learned what Framer Motion is, the motion components and variants. Now it's time to combine them.
Typical flow: write an animated component with motion.div, define states with initial and animate, add enter/leave animation with AnimatePresence.
In the next step you will write a modal that animates on open and close.
Practice Modal open/close animation
Complete the skeleton. Write a ModalSummary component. Keep isOpen (false) with useState. Add <button onClick={() => setIsOpen(true)}>Open</button>. Inside <AnimatePresence> put {isOpen && <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>Content<button onClick={() => setIsOpen(false)}>Close</button></motion.div>}. Import motion and AnimatePresence. Add export default.
Starter code
import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
// Write ModalSummary hereSample solution
import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
function ModalSummary() {
const [isOpen, setIsOpen] = useState(false);
return (
<div>
<button onClick={() => setIsOpen(true)}>Open</button>
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
Content
<button onClick={() => setIsOpen(false)}>Close</button>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
export default ModalSummary;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which topic was NOT covered?
- motion component
- variants
- AnimatePresence
- useTransition hook Correct answer
Explanation: useTransition hook was not covered.
2 AnimatePresence usage
<____>{isOpen && <motion.div />}</AnimatePresence>
<AnimatePresence>{isOpen && <motion.div />}</AnimatePresence>
Explanation: AnimatePresence wraps enter/leave.