Next.js Discord

Discord Forum

[next+gsap] timeline not reversing on effect state change

Answered
Minskin posted this in #help-forum
Open in Discord
MinskinOP
Menu component code: https://mystb.in/8f466eeef4c2dcc869
See Line 31 on wards
Answered by Velvet ant
why dont use the timeline in a event handler instead of a useEffect ? and also you should use the useGSAP hooks https://gsap.com/resources/React#usegsap-hook-

and the thing in your code actually is that your animation is already reversed. I guess it should be something like this

const tl = useRef(gsap.timeline({ paused: true }));

useEffect(() => {
  // Create the timeline once
  tl.current.to(overlayRef.current, {
    clipPath: "polygon(0 0, 100% 0, 100% 100%, 0 100%)",
    duration: 4,
    ease: "power4.inOut",
  });

  // Clean up function
  return () => tl.current.kill();
}, []);

useEffect(() => {
  if (isMenuOpen) {
    tl.current.play();
  } else {
    tl.current.reverse();
  }
}, [isMenuOpen]);


useGSAP helps you with clean up function and other thing with react
View full answer

14 Replies

MinskinOP
I don't know why the intentation is so bad
"trig false" is console logged but no anims are played
Velvet ant
why dont use the timeline in a event handler instead of a useEffect ? and also you should use the useGSAP hooks https://gsap.com/resources/React#usegsap-hook-

and the thing in your code actually is that your animation is already reversed. I guess it should be something like this

const tl = useRef(gsap.timeline({ paused: true }));

useEffect(() => {
  // Create the timeline once
  tl.current.to(overlayRef.current, {
    clipPath: "polygon(0 0, 100% 0, 100% 100%, 0 100%)",
    duration: 4,
    ease: "power4.inOut",
  });

  // Clean up function
  return () => tl.current.kill();
}, []);

useEffect(() => {
  if (isMenuOpen) {
    tl.current.play();
  } else {
    tl.current.reverse();
  }
}, [isMenuOpen]);


useGSAP helps you with clean up function and other thing with react
Answer
Velvet ant
Yep. there is examples in the doc
@Velvet ant Yep. there is examples in the doc
MinskinOP
Oh wait!!! this works!!
Coul you explain why it wasnt working before, im quite lost there
Velvet ant
Sure. in your first code, the timeline was created and cleared each time isMenuOpen changed ( useEffect runs because of isMenuOpen as dependency ) so I guess no way to get the previous state of the animation.
and the timeline was already reversed so I think reversed it again wont work.
MinskinOP
ah makes sense thx
Velvet ant
do you use useGSAP finally ?
MinskinOP
yeah
Velvet ant
and if all is good for you can you set the thread as answered ?
MinskinOP
yes ill do thaat