Jump to content

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

Have to click button twice to run timeline (react)

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()
      x: "-100vw"
      x: 0,
      ease: Cubic.easeInOut

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

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




  • Like 4
Link to comment
Share on other sites



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:



This one uses a state property to toggle the instance:



Happy  Tweening!!!

  • Like 3
Link to comment
Share on other sites

Thank you all so much!! This is amazing, thanks for the quick and great help. Working now!

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