List Animation using Motion for React
reactanimation

List Animation using Motion for React

An in-depth guide on how to animate enter and exit animation for list using Motion for React (previously Framer Motion).

December 17, 2024·6 min·1,250 views·42 reactions·WebsiteFeatured

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.

“

Hope you enjoyed reading.
If this article helped you, consider sharing it with other developers.

AI Companion

Ask questions about this article

Powered by Sant.AI — coming soon