I'm trying to create animated text in React (typescript) using GSAP.
Text variable is a string, which is split into an array of strings, form which separate div's are created for every letter. In order to get this animated with GSAP, every element needs to have its own ref - for now only last letter works as only one ref is assigned.
How to create separate refs for every element and pass them to gsap? Seen somewhere that I should pass a callback as refs, but I'm not sure how to do that.
const TextAnimator: FC<TextAnimatorTypes> = ({ text }) => {
const animatedLetter = useRef(null);
const letterArray = text.split('');
const letterElements = [];
for (let i = 0; i < letterArray.length; i++) {
letterElements.push(<div ref={animatedLetter} className={styles.letter}>{letterArray[i] === ' ' ? '\xa0' : letterArray[i]}</div>);
}
useEffect(() => {
const random = (min: number, max: number) => {
return (Math.random() * (max - min)) + min;
};
gsap.from(animatedLetter.current, {
duration: 2.5,
opacity: 0,
x: 0,
y: random(-200, 200),
z: random(500, 1000),
scale: .1,
delay: 0.2,
yoyo: true,
repeat: -1,
repeatDelay: 4,
ease: Power1.easeOut
});
}, []);
return (
<div className={styles.box}>
<p className={styles.animatedText}>
{letterElements}
</p>
</div>
);
};