Hi, gsappers! I have a question regarding `useState` and `forEach` method.
The issue: I want to switch the animation to the next step depending on the `step` state.
But if I change the state, the animation resets, instead of going seamlessly from the step one to step two and so on.
What could be the reason behind it? Should I create the timeline as a `ref` for each element I want to animate?
Here is the demo — https://codesandbox.io/s/optimistic-sammet-6k76cn?file=/src/App.tsx
Code:
import "./styles.css";
import React from "react";
import gsap from "gsap";
const App = () => {
const flowerCirclesRef = React.useRef<any>([]);
const [step, setStep] = React.useState(0);
const FlowerCircles = () => {
return (
<>
{Array.from(Array(6).keys()).map((i) => {
return (
<div
key={i}
className="flower"
ref={(el) => (flowerCirclesRef.current[i] = el)}
/>
);
})}
</>
);
};
React.useEffect(() => {
flowerCirclesRef.current.forEach((el: any, i: number) => {
if (step === 1) {
gsap.fromTo(
el,
{
transformOrigin: "left center",
opacity: 0,
scale: 0.1,
borderWidth: 3,
left: "50px"
},
{
transformOrigin: "left center",
rotate: 180 * (i / 3),
scale: 1,
opacity: 1,
borderWidth: 1,
duration: 1.3,
delay: i * 0.1,
ease: "elastic.out(0.5,0.9)"
}
);
}
if (step === 2) {
gsap.to(el, {
rotate: 100 * (i / 3),
x: i * 100,
scale: 2,
opacity: 1,
borderWidth: 1,
duration: 1.3,
delay: i * 0.1,
ease: "elastic.out(0.5,0.9)"
});
}
});
}, [step]);
return (
<section className={"wrapper"}>
<button onClick={() => setStep(step + 1)}>Next step</button>
<div className="flowerwrap">
<FlowerCircles />
</div>
</section>
);
};
export default App;
Thank you!