AnimatePresence
AnimatePresence
makes exit animations easy. By wrapping one or more motion
components with AnimatePresence
, we gain access to the exit
animation prop.
Usage
Import
Exit animations
AnimatePresence
works by detecting when its direct children are removed from the React tree.
This can be due to a component mounting/remounting:
Its key
changing:
Or when children in a list are added/removed:
Any motion
components within the exiting component will fire animations defined on their exit
props before the component is removed from the DOM.
Note: Direct children must each have a unique key
prop so AnimatePresence
can track their presence in the tree.
Like initial
and animate
, exit
can be defined either as an object of values, or as a variant label.
Changing key
Changing a key
prop makes React create an entirely new component. So by changing the key
of a single child of AnimatePresence
, we can easily make components like slideshows.
Accessing presence state
When a component is the child of AnimatePresence
, it can use usePresence
to access information about whether it's still present in the React tree.
If isPresent
is false
, it means that a component has been removed the tree, but AnimatePresence
won't remove it until safeToRemove
has been called.
This allows you to do anything you like with AnimatePresence
and its presence state, not just perform animations.
Props
initial
By passing initial={false}
, AnimatePresence
will disable any initial animations on children that are present when the component is first rendered.
custom
When a component is removed, there's no longer a chance to update its props (because it's no longer in the React tree). Therefore we can't update its exit animation with the same render that removed the component.
By passing a value through AnimatePresence
's custom
prop, we can use dynamic variants to change the exit
animation.
mode
Default: "sync"
Decides how AnimatePresence
handles entering and exiting children.
"sync"
: Children animate in/out as soon as they're added/removed."wait"
: The entering child will wait until the exiting child has animated out. Note: Currently only renders a single child at a time."popLayout"
: Exiting children will be "popped" out of the page layout. This allows surrounding elements to move to their new layout immediately.
Custom component note: When using popLayout
mode, any immediate child of AnimatePresence that's a custom component must be wrapped in React's forwardRef
function, forwarding the provided ref
to the DOM node you wish to pop out of the layout.
onExitComplete
Fires when all exiting nodes have completed animating out.
Motion is open source. Sponsorships keep the project sustainable.
Every sponsor receives access to our private Discord, and an exclusive mobile and desktop wallpaper pack.