I'm trying to animate an element with gsap
in react.js
.
My code works only when react hot reloads and in console I have warning from gsap saying GSAP target not found
const FeaturedText = () => {
const tl = gsap.timeline({ repeat: 0 });
useEffect(() => {
animation(tl);
}, []);
return <S.FeaturedText className="tl">Hi! Some Text</S.FeaturedText>;
};
const animation = (tl) => {
tl.from(".tl", {
opacity: 0,
duration: 1,
x: 100,
ease: "elastic",
delay: 2,
});
};
Firstly we need to get access to the element that we want to animate.
In react we use
useRef
hook to get a component's reference and then use gsap to animate it.
I'll explain how to animate a component in react properly.
//initialize useRef
let featuredText = useRef(null);
//start animation only when dom components are mounted.
useEffect(() => {
const tl = gsap.timeline({ repeat: 0 });
animation(tl, featuredText);
}, []);
//Animation
const animation = (tl, el) => {
tl.from(el, {
opacity: 0,
duration: 1,
x: 100,
ease: "elastic",
delay: 2,
});
};
//Component to be animated
return (
<S.FeaturedText ref={(el) => (featuredText = el)} className="tl">
Hi! I'm Raghav
</S.FeaturedText>
);