Animate Presence

Documentation

Animate Presence

Reading Time:

5

min

Released

September 8, 2023

Animate components when they're removed from the React tree.

AnimatePresence allows components to animate out when they're removed from the React tree.

It's required to enable exit animations because React lacks a lifecycle method that:

  1. Notifies components when they're going to be unmounted and

  2. Allows them to defer that unmounting until after an operation is complete (for instance an animation).

import { motion, AnimatePresence } from "framer-motion"

export const MyComponent = ({ isVisible }) => (
  <AnimatePresence>
    {isVisible && (
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
      />
    )}
  </AnimatePresence>
)


Usage

Exit animations

AnimatePresence works by detecting when direct children are removed from the React tree.

Any motion components contained by the removed child that have an exit prop will fire that animation before the entire tree is finally removed from the DOM.

Note: Direct children must each have a unique key prop so AnimatePresence can track their presence in the tree.

const MyComponent = ({ isVisible }) => (
  <AnimatePresence>
    {isVisible && (
      <motion.div
        key="modal"
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
      />
    )}
  </AnimatePresence>
)

Istanbul

Follow us on social media