Jump to content
Search Community

Have to click button twice to run timeline (react)

elit test
Moderator Tag

Recommended Posts

Hi there,

 

My sidenav function is working fine, however when I first run toggleMenu() I have to run it twice the first time for it to fire - is there a better way to do this?

 

Codesandbox is https://codesandbox.io/s/focused-montalcini-ejxnu

 

Thank you

Link to comment
Share on other sites

 

Hey @elit - welcome to the forums.

 

Since you are using a check on the reversed state for the animation play-state handling

 

tl.reversed() ? tl.play() : tl.reverse();

 

 you'd want to set your timeline to reversed initially to make it work as expected.

 

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

 

Does that work better for you?

 

 

  • Like 4
Link to comment
Share on other sites

I think should work better for you. NEVER create an animation inside a function like that with React. It will lead to problems later on once you start introducing state changes.

 

const tl = useRef();
const wrapperRef = useRef(null);

useEffect(() => {
  tl.current = gsap.timeline()
    .fromTo(
    wrapperRef.current,
    {
      x: "-100vw"
    },
    {
      x: 0,
      ease: Cubic.easeInOut
    }
  ).reverse();

  return () => tl.current.kill();
}, []);

const toggleMenu = () => {
  tl.current.reversed() ? tl.current.play() : tl.current.reverse();
};

 

 

 

  • Like 4
Link to comment
Share on other sites

Hi,

 

Just to add on Paul and Blake great advice, here are a couple of live samples in React that toggle a GSAP instance.

 

This one uses a regular click handler:

https://codesandbox.io/s/simple-gsap-instance-toggle-xc741

 

This one uses a state property to toggle the instance:

https://codesandbox.io/s/gsap-toggle-instance-with-hooks-t9uqr

 

Happy  Tweening!!!

  • Like 3
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...