How to use Scrolltrigger with timeline in React

 
  gsap.registerPlugin(ScrollTrigger);

  const myRef = useRef(null);
  const mySecRef = useRef(null);

  useEffect(() => {
    var tl = gsap.timeline({
      scrollTrigger: {
        trigger: myRef.current,
        start: "top top",
        end: "3500 bottom",
        scrub: true,
        pin: true,
      },
    });

    tl.to(myRef.current, {
      scale: 0.3,
    });
    tl.to(myRef.current, {
      x: "25%",
    });
    tl.fromTo(
      mySecRef.current,
      {
        opacity: 0,
      },
      { opacity: 1 }
    );
  });
  

In the snippet above, i am referencing two elements as an example, but you can reference as many as you want, and add them accordingly to the Gsap timeline. Simply reference the elements in the DOM that you want to animate, and tweak the timeline as you prefer.


  <div ref={myRef}>
  </div>
  <img
     ref={mySecRef}
     src=""
     alt=""
    />
  

Make sure to import the React Hooks, Gsap and the Scrolltrigger plugin. If your react app is server side rendering (so if you are using Next.js, Gatsy, Remix, etc), you have to import it from the dist folder of the Scrolltrigger plugin.


  import React, { useRef, useEffect } from "react";
  import { gsap } from "gsap";
  import { ScrollTrigger } from "gsap/ScrollTrigger";
  

  import { ScrollTrigger } from "gsap/dist/ScrollTrigger";