Jump to content
Search Community

GSAP ScrollTrigger doesnt work on box

mikoo1991 test
Moderator Tag

Recommended Posts

Hello,

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;

 

Link to comment
Share on other sites

It looks like you've got a duplicate post at https://stackoverflow.com/questions/74480009/gsap-scrolltrigger-doesnt-work-with-my-box/74480677#74480677

 

I'll paste my response here...

 

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:


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

 

Here's a CodeSandbox starter template for React that you can fork to create a minimal demohttps://codesandbox.io/s/gsap-react-starter-ut42t

 

Happy tweening!

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...