Jump to content
Search Community

GSAP in React component - Animation can't remember current position

moleboy test
Moderator Tag

Go to solution Solved by Rodrigo,

Recommended Posts

Hi,

 

I've built a component which lays out a number of buttons from an Array that is passed in as a prop and there is a marker that animates to highlight which button is pressed. State is handled by the parent component. I can see animation but each time I press a button it starts from 0px rather than animating from its current position.

 

I'm sure this is a fairly basic error that I'm doing but having read the docs I'm struggling.

 

Could some kind soul please take a look and see where the error might be in my code?  I'd be very grateful.

 

Here is the child component code

 

import { gsap } from "gsap";
import PropTypes from "prop-types";
import { useLayoutEffect, useRef } from "react";

function SlideToggle({ buttonArray, handleClick, currentIndex }) {
  const sendValueToParent = (value) => {
    handleClick(value);
  };

  // gsap code for toggle marker
  const component = useRef(null);

  useLayoutEffect(() => {
    let ctx = gsap.context(() => {
      gsap.to(".slide-marker", {
        x: currentIndex * 40,
        duration: 0.5,
      });
    }, component);

    return () => ctx.revert(); // cleanup!
  }, [currentIndex]);

  const buttonElements = buttonArray.map((el, index) => (
    <button
      className="w-[30px] h-[30px] flex justify-center items-center text-white"
      key={index}
      onClick={() => sendValueToParent(index)}
    >
      {el.icon}
    </button>
  ));

  return (
    <div className="relative" ref={component}>
      <div className="slide-marker w-[30px] h-[30px] absolute bg-white bg-opacity-10 top-0 pointer-events-none"></div>
      <div className="flex space-x-[10px]">{buttonElements}</div>
    </div>
  );
}

export default SlideToggle;

SlideToggle.propTypes = {
  buttonArray: PropTypes.array,
  handleClick: PropTypes.func,
  currentIndex: PropTypes.number,
};

 

Link to comment
Share on other sites

It's pretty tough to troubleshoot without a minimal demo - the issue could be caused by CSS, markup, a third party library, your browser, an external script that's totally unrelated to GSAP, etc. Would you please provide a very simple CodePen or Stackblitz that demonstrates the issue? 

 

Please don't include your whole project. Just some colored <div> elements and the GSAP code is best (avoid frameworks if possible). See if you can recreate the issue with as few dependancies as possible. If not, incrementally add code bit by bit until it breaks. Usually people solve their own issues during this process! If not, then at least we have a reduced test case which greatly increases your chances of getting a relevant answer.

 

Here's a starter CodePen that loads all the plugins. Just click "fork" at the bottom right and make your minimal demo

See the Pen aYYOdN by GreenSock (@GreenSock) on CodePen

 

If you're using something like React/Next/Vue/Nuxt or some other framework, you may find StackBlitz easier to use. We have a series of collections with different templates for you to get started on these different frameworks: React/Next/Vue/Nuxt.

 

Once we see an isolated demo, we'll do our best to jump in and help with your GSAP-specific questions. 

Link to comment
Share on other sites

  • Solution

Hi,

 

This is mostly a JS scope issue. When you change the target element you are creating a new instance of GSAP Context each time:

useLayoutEffect(() => {
  let ctx = gsap.context(() => {
    gsap.to('.slide-marker', {
      x: currentIndex * 30,
      duration: 0.5,
    });
  }, component);

  return () => ctx.revert(); // cleanup!
}, [currentIndex]);

Is better to create your GSAP Context just once and add a method to it in order to call that method when the currentIndex prop changes:

useLayoutEffect(() => {
  ctx.current && ctx.current.doAnimation(currentIndex);
}, [currentIndex]);

useLayoutEffect(() => {
  ctx.current = gsap.context((self) => {
    self.add("doAnimation", (target) => {
      gsap.to('.slide-marker', {
        x: target * 30,
        duration: 0.5,
      });
    });
  }, component);

  return () => ctx.current.revert(); // cleanup!
}, []);

That seems to work the way you intend:

https://stackblitz.com/edit/gsap-react-basic-f48716-gqswdm?file=src%2FSlideToggle.js

 

Take a better look at the GSAP Context docs:

https://greensock.com/docs/v3/GSAP/gsap.context()

 

Finally I'd recommend you to check the resources in this page:

 

Hopefully this helps.

Happy Tweening!

Link to comment
Share on other sites

Thanks very much Rodrigo, I figured it might be because I kept creating a new context on render but wasn't sure on the syntax to address that. I can follow what you've done.

 

I did look over all the documentation but I think I was struggling to find a concrete example that mapped to my specific use case.

 

Appreciate the help!

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