Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...
Christopher Evans

gsap.reverse() not working on onMouseLeave in React

Go to solution Solved by nico fonseca,

Recommended Posts

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 the recommendations here and here.

 

Code sandbox

Link to comment
Share on other sites

  • Solution

Hey @Christopher Evans
Something like this ?
 

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

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


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

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


Sorry for the "any", I'm not TS expert. I think @OSUblake is the best for this 😅

 

  • Like 3
Link to comment
Share on other sites

@nicofonseca This did indeed work, thank you!

Why does this require a timeline rather than a tween, though? I was working under the notion that timelines are for stringing multiple tweens together. As this is jut one animation, I thought the tween (which is the default type of the default gsap export, right?) would suffice.

Link to comment
Share on other sites

In the const tl I only set one tween not a timeline (sorry for the confusing name) 😅
 

  • Like 3
Link to comment
Share on other sites

4 hours ago, nicofonseca said:

Sorry for the "any", I'm not TS expert. I think @OSUblake is the best for this 😅

 

It would be like this...

const myTween = useRef<GSAPTween>();
const myTimeline = useRef<GSAPTimeline>();

 

  • Like 2
  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×