Jump to content

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

Toggle width with play() and reverse()

Recommended Posts

I have a React component that I'm trying to toggle the width of when a button is clicked. When the button is clicked again, it goes back to the original width.


The problem is the original width could be anything, depending on the viewport size as it's responsive. On small devices it's 75%, large it's 25% with a few others in the middle. There's also another animation that animates the opacity and position of the element I'm targeting here.


Here's what I have so far;



useEffect(() => {
  const tween = gsap.to(slashRef.current, {
    width: '100%',
    ease: 'power3',
    paused: true,

  if (menuOpen) {
  } else {
}, [menuOpen]);


I've tried starting it as paused, and when the `menuOpen` is true it animates the width fine. When it's `false` it's not reversing it back to its original position as I would expect — clearly I'm missing something.


I've tried a bunch of different approaches using state and ref to set the original width and trying to access that but I've had no joy so far. I'm sure it's something simple I'm missing.


Thanks for any help,



Link to comment
Share on other sites

Hey ccld and welcome to the GreenSock forums!


To me this sounds like an issue where the animation value is cached when it's instantiated and it doesn't match the value when you are actually wanting it to animated. Without seeing a demo of the issue it's pretty hard to know if that's the case though :) 


Can you please create a minimal demo using something like CodeSandbox so that we can take a look for ourselves? 

Link to comment
Share on other sites

How could you add a delay to this? I tried adding delay: 0.25 to the tween but it didn't do anything


Edit: delayedCall() seems to do the trick :-)

Edited by ccld
Link to comment
Share on other sites

Hm... delay is when it first starts, but that tween has already started, it's just reversed.


You can use a timeline instead.

tween.current = gsap.timeline()
  .to(box.current, { x: 300 },0.25);


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