Jump to content
Search Community

Toggling an animation of items in and out with useGSAP and state in a React component

henryb test
Moderator Tag

Recommended Posts

Hello,


I'm trying to animate a nav opening and items animating as part of a timeline animation, in a Next.JS app. I'm using the useGSAP hook and a gsap timeline to stagger the animation in of menu items in the nav, and then I want to toggle the animation in reverse when the nav is closed.

My issue is that the menu items are currently fetched from a CMS using a useEffect when the component mounts, and those items are set in state. But when I animate the nav, the items in state do not animate. 

Here is a linked Stackblitz repoduction of my issue: Stackblitz reproduction

 

My impression is that I'm misunderstanding how React lifecycles work here with useGSAP, but I would be grateful for any pointers that anyone is able to offer. Many thanks in advance!

P.S. In my app I'm using Next.JS 14 with the Pages router, rather than the App router as in this Stackblitz, but the only aspect that changes is how I would fetch data in the component, so it should not pertain to the issue I am facing specifically.

Link to comment
Share on other sites

Hi,

 

If you want to create a GSAP instance based on a state that will be updated during the lifecycle of the app, then use the dependencies and revertOnUpdate options, in order to tell useGSAP to re-run the code once that state is up-to-date. This seems to work the way you expect:

useGSAP(
  () => {
    const menu = gsap.utils.toArray('.menu');
    tl.current = gsap
      .timeline()
      .to(nav.current, {
        height: '80vh',
        background: '#F5F4F0',
        duration: 0.75,
      })
      .from(menu, { y: -8, opacity: 0, stagger: 0.05 })
      .to(menu, { y: 0, opacity: 1, stagger: 0.05, duration: 0.1 })
      .reverse();
  },
  {
    scope: nav,
    dependencies: [artists],
    revertOnUpdate: true,
  }
);

useEffect(() => {
  tl.current?.reversed(!isNavOpen);
}, [isNavOpen]);

Hopefully this helps.

Happy Tweening!

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.
×
×
  • Create New...