0

I am new to gsap and trying to make some animations on it, but when I set gsap to my header it doesn't work. Here is my code:

import { gsap } from "gsap";

  let tl = gsap.timeline();

  useEffect(() => {
    tl.from(".lastHeader", { y: 50, duration: 1 });
  }, []);

thanks in advance.

Myrat
  • 347
  • 2
  • 4
  • 16
  • Hi! Check does element `.lastHeader` was transformed? Try to add `let tl = gsap.timeline({paused: true})` and then after create `tl` (`tl.from(...)`) try to call `tl.play()`. Or try to add `let tl = gsap.timeline({repeat: -1, yoyo: true})` and check does animation play infinite – Greg-- Feb 07 '22 at 09:05
  • `.lastHeader` is a span element, thats why it doesnt work, but why? I tried using it with div element, it works fine. Why doesn't it work with span element? – Myrat Feb 07 '22 at 16:28
  • Because css transform does not apply to inline elements, you can change css to `display: inline-block` more detail https://stackoverflow.com/a/24962108/14135825 – Greg-- Feb 07 '22 at 16:47

3 Answers3

0
import { gsap } from "gsap";

tl = useRef()

  useEffect(() => {
    tl.current = gsap.timeline();
    .from(".lastHeader", { y: 50, duration: 1 });
  }, []);

You can use code like this.

Jeff Schaller
  • 2,352
  • 5
  • 23
  • 38
0

In order to avoid creating a new timeline on every render, it's important to create the timeline inside an effect and store it in a ref.

This will also allow u to access the timeline in a different effect.

see example here:

function App() {
  const el = useRef();
  const q = gsap.utils.selector(el);
  const tl = useRef();
      
  useEffect(() => {            
    
    tl.current = gsap.timeline()
      .to(q(".box"), {
        rotate: 360
      })
      .to(q(".circle"), {
        x: 100
      });

  }, []);
  
  return (
    <div className="app" ref={el}>
      <Box>Box</Box>
      <Circle>Circle</Circle>
    </div>
  );
}

More info here: https://greensock.com/react/

0

You have to define timeLine variable outside of useLayoutEffect.

const comp = useRef(null);
const tl = useRef<gsap.core.Timeline | null>(null);

useLayoutEffect(() => {
  const ctx = gsap.context(() => {
    tl.current = gsap
      .timeline()
      .from("your-element", {
        duration: 4,
        delay: 0.4,
        opacity: 0,
        y: 200,
        ease: "power3.inOut",
      })
     }, comp);
     return () => ctx.revert(); // cleanup
 }, []);
jsina
  • 4,433
  • 1
  • 30
  • 28