List Animation using Motion for React
Animating lists in React can be tricky, especially when dealing with enter and exit animations. In this post, we'll explore how to use Motion for React to create smooth list animations.
Getting Started
First, install the package:
npm install framer-motion
AnimatePresence
The key component for exit animations is AnimatePresence. It keeps track of components that are being removed from the tree.
import { AnimatePresence, motion } from 'framer-motion';
function List({ items }: { items: string[] }) {
return (
<AnimatePresence>
{items.map((item) => (
<motion.li
key={item}
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
>
{item}
</motion.li>
))}
</AnimatePresence>
);
}
Staggered Animations
You can stagger animations using staggerChildren in the parent variant.
Conclusion
Motion for React makes list animations straightforward and performant.
