React › Animation in React (Framer Motion & React Spring)
How would you animate a list where items can be added or removed, such as a shopping cart?
IntermediateAnswer
Framer Motion provides an AnimatePresence component that detects when an item is removed from a list and plays an exit animation before it actually disappears from the screen, instead of the item just vanishing suddenly.
import { motion, AnimatePresence } from 'framer-motion';
function CartList({ items }) {
return (
<AnimatePresence>
{items.map((item) => (
<motion.li key={item.id} exit={{ opacity: 0, x: -50 }}>
{item.name}
</motion.li>
))}
</AnimatePresence>
);
}Real-world example An online store animates each product sliding out smoothly when a customer removes it from their shopping cart, instead of the item disappearing instantly and confusing the user.