Exit animation: Step-by-step tutorial

Matt Perry
In this tutorial, we're going to build the Exit animation example step-by-step.
This tutorial is rated 1/5 difficulty, which means we'll spend some time explaining the Motion APIs that we've chosen to use (and why), and also any browser APIs we encounter that might be unfamiliar to beginners.
Here's a live demo of the example we're going to be creating:
Introduction
The Exit animation example shows how to animate an element before it's removed from the DOM. It uses the AnimatePresence
component and exit
prop from Motion for React to create smooth transitions when elements are removed.
CSS animations can only handle when elements appear, and even then only with the modern @starting-style
rule. They can't handle when elements leave.
Whereas JS animations need careful orchestration to handle when elements leave.
AnimatePresence
is a React component that makes it easy to animate elements when they exit.
Get started
Let's start by creating a component with a box that can be toggled on and off:
This creates a simple component with a red box and a button that toggles the box's visibility. Currently, the box just instantly appears and disappears when toggled.
Let's animate!
Import from Motion
To animate our box as it enters and exits, we need to import the necessary components from Motion for React:
Let's replace our standard div
with a motion.div
:
This alone won't give us exit animations. For that, we need to wrap our conditionally rendered element in AnimatePresence
:
Animations
Now we can add our animation properties. We'll need:
An
initial
state for when the element first appears.An
animate
state for its normal visible state.An
exit
state for how it should animate out before being removed from the DOM byAnimatePresence
.
With these props:
The box starts invisible and scaled down to nothing
It animates to fully visible and full size when it appears
When toggled off, it animates back to invisible and scaled down before being removed from the DOM
A couple important details:
We set
initial={false}
onAnimatePresence
to prevent the initial animation when the component first loadsWe added a
key
to our motion component, which is required forAnimatePresence
to track elements properly
Adding button animation
Let's also add a small animation to the button when it's pressed:
The whileTap
prop moves the button down slightly when pressed, creating a satisfying tactile feel.
Conclusion
In this tutorial, we learned how to:
Create exit animations using the
AnimatePresence
componentDefine enter and exit animations with the
initial
,animate
, andexit
propsCreate a toggle effect with state and conditional rendering
Add tactile feedback to interactive elements with
whileTap
Motion for React makes it easy to add these polished transitions to your UI, improving the user experience by maintaining visual continuity when elements are added or removed.