Animate Elements Removed from the DOM with Framer Motion Animate Presence

Will Johnson
InstructorWill Johnson
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

AnimatePresence allows components to animate when they're removed from the React tree. Once the elements are wrapped in AnimatePresence you get access to the exit prop which animate the element when it is removed.

Instructor: [0:01] As you can see, if we add a new list item, it animates onto the screen, but when we remove it, it doesn't animate out. That's not a good experience for our users. We want the experience to be consistent on how items are removing and adding to the DOM.

[0:22] In order for us to do this in Framer Motion, we can use the AnimatePresence component. To use AnimatePresence, we would import AnimatePresence from Framer Motion.

[0:36] After AnimatePresence is imported, we're going to wrap it around the item that we want to animate out of the DOM. I will wrap it around the items that we want to map over in our list. Make sure you add that closing tag. Also, when using AnimatePresence, you want to make sure that you have a key prop on what you're animating. For this, I set the key to item.id.

[1:11] Now that we have our elements wrapped in the AnimatePresence component, we get access to a special prop called exit. Exit is what allows the element to actually be removed from the DOM and allow it to be animated. We're going to set it to hidden, which is our variant label. We'll save that.

[1:35] Now, when the item is removed from the DOM, it will go back to the hidden state, which will be invisible. As we save that, let's remove it. As you see, now, it fades out. Let's test it again. Test, then remove.

[1:53] To recap, we've imported AnimatePresence from Framer Motion. We wrapped items in the AnimatePresence component. We made sure that we had our key prop, and then we added the exit prop and set it to hidden. Now, our list item will animate when it leaves the DOM.

egghead
egghead

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today