Hi All,
I write little useful code snippets without lots of words. This will be about making your own React mount / unmount animation without using any library. We will take advantage of javascript animationend event. (onAnimationEnd in React.js)
First of All we prepare our styles.
.animated-render-show {
animation: fadeIn 0s;
}
.animated-render-hide {
animation: fadeOut 0s;
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes fadeOut {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
Then we are writing our animated render code.
import { Children, useState, useEffect, cloneElement } from "react";
import "./style.css";
export default function AnimatedRender({
children,
mountAnimationClass = "animated-render-show",
unmountAnimationClass = "animated-render-hide",
visible = true
}) {
const [show, setShow] = useState(visible);
const animatedClassName = visible
? mountAnimationClass
: unmountAnimationClass;
useEffect(() => {
if (visible) {
setShow(true);
}
}, [visible]);
const handleAnimationEnd = () => {
if (!visible) {
setShow(false);
}
};
const clonedChildren = Children.map(children, (child) => {
const classNameWithAnimate = `${
child.props.className || ""
} ${animatedClassName}`;
return cloneElement(child, {
className: classNameWithAnimate,
onAnimationEnd: handleAnimationEnd
});
});
return show && clonedChildren;
}
By default mountAnimation class and unmountAnimation class has animated 0 second duration. This is because of the way of the works onAnimationEnd. If your element has not an animation, onAnimationEvent will not work.
You can found working version of it in this link: React Mount / Unmount Animation
Top comments (0)