The Problem:
When using the useAnimate
hook with the useInView
hook, elements jump from 0 to 100 at the first keyframe. How can I set an initial value to prevent this jump?
The Solutions:
Solution 1: Use CSS to set initial values
When using useAnimate
with useInView
, set initial values in the CSS file. The CSS value should match the initial state of the element. Then, use animate
to transition the element to its desired state. Avoid using class names to refer to elements; instead, refer to them directly using HTML tags (e.g., "span" or "p").
Example:
const [animationScope, animateSpan] = useAnimate();
useEffect(() => {
if (isInView) {
animateSpan('span', { y: 0 }, { duration: 1, delay: staggerChildren(0.15) })
}
}, [isInView]);
//jsx returned:
<div ref={animationScope}>
<motion.span></motion.span>
</div>
In this example, the span
elements have an initial transform: translateY(100)
in the CSS. Then, when the isInView
state changes to true
, useAnimate
transitions the span
elements to y: 0
.
Q&A
How to add an initial value to the element when working with useAnimate
?
Assign the initial values in the CSS file instead of using the initial
prop in useAnimate
. When the point in time comes to animate the element(s), pass the value(s) to the animate
method that you’d want it to jump to.
Video Explanation:
The following video, titled "Framer Motion (for React) #11 - Animate Presence - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.
Hey gang, in this Framer Motion tutorial we'll take a look at the AnimatePresence component to animate elements exiting the DOM.
The following video, titled "Framer Motion (for React) #11 - Animate Presence - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.
Hey gang, in this Framer Motion tutorial we'll take a look at the AnimatePresence component to animate elements exiting the DOM.