DEV Community

Medusa
Medusa

Posted on

Easily animate React components when mount/unmount 😅

Example 1

One of the things that I have neglected the most as a React programmer when it comes to animations is the transitions when mounting and unmounting a component. Normally I always left without animations because I didn't see an easy and comfortable way to put them either. The result is quite forced and the experience for the user is that things appear and disappear by magic, nothing fluid.

Until a couple of days ago I decided to investigate the best and simplest way to run animations when mounting and unmounting components. I came to the conclusion that the best thing was to create a generic component that allows mounting and unmounting components through the simplest possible syntax.

I started creating a component that would manage the animation of the component and take care of mounting and unmounting it when indicated. The animation had to be done using the CSS keyframes, so I came up with a solution like this simple example:

Instead of this (mount/unmount without animation):

const MyComponent = () => {
  const [isMounted, setIsMounted] = useState(false);

  ...

  return (
   <>
      {isMounted && (
        <div>
          Hi World!
        </div>
      )}
   </>
)
...
Enter fullscreen mode Exit fullscreen mode

We do this (same with animation):

import Animated from "react-mount-animation";

const MyComponent = () => {
  const [isMounted, setIsMounted] = useState(false);

  ...

  return (
      <Animated.div //You can use any HTML element here
        show={isMounted}
        mountAnim={` 
            0% {opacity: 0}
            100% {opacity: 1}
        `}
      >
        Hi World!
      </Animated.div>
)
...
Enter fullscreen mode Exit fullscreen mode

Anyone who wants to collaborate on it can contact me and any technical or non-technical opinion I will receive with pleasure. Maybe this package does not make sense, maybe it does, in any case I would love for you to leave a comment.

If you want to inspect the code or simply test it, you can do it by consulting the repository: https://github.com/mijim/react-mount-animation

https://www.npmjs.com/package/react-mount-animation

Thanks & Happy Coding! ⚡️

Top comments (1)

Collapse
 
kellygue profile image
Kelly Guelcé • Edited

Very useful
Thank you !!! :)