Skip to main content

How to create exit animations with Framer Motion

00:00:57:33

Introduction to Exit Animations

Animations are a key part of modern web applications. They make interfaces feel alive and responsive. In React, animating elements when they appear is straightforward. However, animating elements when they leave the DOM (exit animations) can be tricky because React immediately unmounts them before any animation can complete.

That's where Framer Motion's AnimatePresence comes in. It allows you to animate elements as they exit the DOM.

jsx
import { motion, AnimatePresence } from 'framer-motion';

function ToggleComponent({ isVisible }) {
  return (
    <AnimatePresence>
      {isVisible && (
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: 20 }}
        >
          I will animate when entering and leaving!
        </motion.div>
      )}
    </AnimatePresence>
  );
}

How AnimatePresence Works

When a child of AnimatePresence is removed from the React tree, AnimatePresence will defer unmounting the child until the exit animation has fully completed. This enables seamless transition flows, which are particularly important for things like modal overlays, slide-out menus, or list removals.

Stay tuned for more React animation tips!