Home > Enterprise >  GSAP ScrollTrigger doesnt work with my box
GSAP ScrollTrigger doesnt work with my box

Time:11-18

I am trying to learn GSAP and i want some elements to slide into view when scrolling, and I found a ScrollTrigger plugin for GSAP. However, it doesnt work. It slides back when scrolling up, but when scrolling down, nothing shows up.

import { useLayoutEffect, useState } from "react";
import reactLogo from "./assets/react.svg";
import "./App.css";
import gsap from "gsap";
import styled from "styled-components";

import { ScrollTrigger } from "gsap/dist/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger);

const Container = styled.div`
  height: 4000px;
`;

function App() {
  const [count, setCount] = useState(0);

  useLayoutEffect(() => {
    gsap.from(".box", {
      scrollTrigger: {
        trigger: ".box",
        start: "top center",
        end: "bottom center",
        scrub: true,
        markers: true,
      },
      x: -1500,
      opacity: 0,
    });
  }, []);

  return (
    <>
      <Container>Hello World</Container>
      <div
        className="box"
        style={{ backgroundColor: "red", width: 300, height: 300 }}
      ></div>
      <Container></Container>
    </>
  );
}

export default App;

CodePudding user response:

I noticed a few problems:

  1. You're importing the regular gsap module (good) but then you're importing the non-module ScrollTrigger (from the /dist/ directory). You should just import ScrollTrigger from "gsap/ScrollTrigger" (or import both gsap and ScrollTrigger from /dist/ - just be consistent)
  2. You're probably getting bitten by the React double-call of useLayoutEffect() in strict mode which messes with "from()" tweens. That's easily solved by using gsap.context() which we'd STRONGLY recommend in any React environment.

Please read the article about using GSAP in React here: https://greensock.com/react

It illustrates how to use gsap.context() too.

If you're still having trouble, feel free to post in the forums at https://greensock.com/forums along with a minimal demo and we'd be happy to take a peek and answer any GSAP-related questions.

Happy tweening!

  • Related