crevulus
crevulus

Reputation: 2458

gsap.reverse() not working on onMouseLeave in React

I am integrating simple gsap animations into my React application. I can trigger a animation.play() fn on onMouseEnter, but the animation.reverse() fn is not working.

Here's my set up:

const hoverScaleAnimation = (
ref: MutableRefObject<HTMLDivElement | null>
) => {
  return gsap.to(ref.current, { scale: 1.05 });
};

const onEnter = (ref: MutableRefObject<HTMLDivElement | null>) => {
  hoverScaleAnimation(ref).play();
};

const onLeave = (ref: MutableRefObject<HTMLDivElement | null>) => {
  hoverScaleAnimation(ref).reverse();
};

Originally I was just triggering new gsap.to animations in the hover functions, but I thought this would be cleaner/less need to calculate how to scale and de-scale.

I am following these react & gsap guidelines from greensock, and tried to use reverse() in line with their recommendations here and here.

Code sandbox

Upvotes: 0

Views: 371

Answers (1)

crevulus
crevulus

Reputation: 2458

Answered on the greensock forum: https://greensock.com/forums/topic/29212-gsapreverse-not-working-on-onmouseleave-in-react/

The solution is to create a tween, run it in useEffect but instantiate it as paused, then play and reverse on hover:

const itemRef = useRef<HTMLDivElement>(null);
const tween = useRef<any>(null);

useEffect(() => {
  tween.current = gsap.to(itemRef.current, { scale: 1.05, paused: true});
}, []);

const onEnter = () => {
  tween.current.play();
};

const onLeave = () => {
  tween.current.reverse();
};

Upvotes: 1

Related Questions