Jump to content
Search Community

When using gsap in React

junH
Moderator Tag

Recommended Posts

Posted

There is a ScrollTrigger hanging in the black section. If you scroll down quickly, and stop just above the starting point of the black section, the ScrollTrigger turns onEnter and then turns onLeaveBack immediately. I'd really appreciate it if you could tell me how to fix it. 🙏

 

Please refer to the video.

 

If you look at the video, it works normally at first, but the problem I explained occurs at the second time. 😭😭

 

import React, { useEffect } from 'react'
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/all'

import './App.css'

// gsap
gsap.registerPlugin(ScrollTrigger);

const App = () => {

  useEffect(() => {

    ScrollTrigger.create({
      trigger: "#item1",
      start: "top top",
      end: "+=2000 bottom",
      scrub: true,
      pin: true,
      anticipatePin: 1,
      markers: true,
      onEnter: () => {console.log('onEnter')},
      onLeaveBack: () => {console.log('onLeaveBack')}
    });

  }, [])

  return (
    <div>
      <section id='margin'></section>
      <section id='item1'>
        <div className='content'>content</div>
      </section>
      <section id='item2'></section>
    </div>
  )
}

export default App

 

Posted

Hi there! I see you're using React -

Proper cleanup is very important with frameworks, but especially with React. React 18 runs in strict mode locally by default which causes your useEffect() and useLayoutEffect() to get called TWICE.

 

Since GSAP 3.12, we have the useGSAP() hook (the NPM package is here) that simplifies creating and cleaning up animations in React (including Next, Remix, etc). It's a drop-in replacement for useEffect()/useLayoutEffect(). All the GSAP-related objects (animations, ScrollTriggers, etc.) created while the function executes get collected and then reverted when the hook gets torn down.

 

Here is how it works:

const container = useRef(); // the root level element of your component (for scoping selector text which is optional)

useGSAP(() => {
  // gsap code here...
}, { dependencies: [endX], scope: container }); // config object offers maximum flexibility

Or if you prefer, you can use the same method signature as useEffect():

useGSAP(() => {
  // gsap code here...
}, [endX]); // simple dependency Array setup like useEffect()

This pattern follows React's best practices.

 

We strongly recommend reading the React guide we've put together at https://gsap.com/resources/React/

 

If you still need help, here's a React starter template that you can fork to create a minimal demo illustrating whatever issue you're running into. Post a link to your fork back here and we'd be happy to take a peek and answer any GSAP-related questions you have. Just use simple colored <div> elements in your demo; no need to recreate your whole project with client artwork, etc. The simpler the better. 

  • 2 weeks later...
Posted
import React, { useRef } from 'react'
import styled from 'styled-components'
import gsap from 'gsap'
import { useGSAP } from '@gsap/react'
import { ScrollTrigger } from 'gsap/ScrollTrigger'

gsap.registerPlugin(ScrollTrigger)

const UseGSAPContainer = styled.main`
margin-top: 700px;
height: 200vh;
.box1{
   width: 100%;
   height: 400px;
   background-color: red;
}
`

const UseGSAP = () => {

   const box1 = useRef();

   useGSAP(() => {

      gsap.to(box1.current, {
         scrollTrigger: {
            trigger: box1.current,
            pin: true,
            start: "top top+=500",
            end: "bottom top+=300",
            anticipatePin: 1,
            scrub: true,
            markers: true,
            onEnter: () => { console.log('onEnter') },
            onLeaveBack: () => { console.log('onLeaveBack') }
         }
      })

   })

   return (
      <UseGSAPContainer>
         <div className='container-1440 xl:mt-200'>
            <div
               ref={box1}
               className='box1 box'
            />
         </div>
      </UseGSAPContainer>
   )
}

export default UseGSAP

 

 

Hello, as mentioned, I implemented the feature using useGSAP. However, the same error occurs as shown in the video I shared earlier.😭😭😭

If you take a look at the attached screenshot, you can see that the onEnter event is triggered even though scroller-start and start haven't met. The red rectangle visibly pins to the scroller-start position. Then, approximately 0.1 seconds later, the onLeaveBack event is triggered, causing the red rectangle to return to its original position. This results in a jerky motion that appears to be a glitch.

2025-01-085_26_42.thumb.png.89528906bd496c27c232b473e32df381.png 😭😭😭😭

GSAP Helper
Posted

Without a minimal demo, it's very difficult to troubleshoot; the issue could be caused by CSS, markup, a third party library, a 3rd party script, etc. Would you please provide a very simple CodePen or Stackblitz that illustrates the issue? 

 

Please don't include your whole project. Just some colored <div> elements and the GSAP code is best. See if you can recreate the issue with as few dependencies as possible. Start minimal and then incrementally add code bit by bit until it breaks. Usually people solve their own issues during this process! If not, at least we have a reduced test case which greatly increases your chances of getting a relevant answer.

 

See the Pen aYYOdN by GreenSock (@GreenSock) on CodePen.

that loads all the plugins. Just click "fork" at the bottom right and make your minimal demo

 

Using a framework/library like React, Vue, Next, etc.? 

CodePen isn't always ideal for these tools, so here are some Stackblitz starter templates that you can fork and import the gsap-trial NPM package for using any of the bonus plugins: 

 

Please share the StackBlitz link directly to the file in question (where you've put the GSAP code) so we don't need to hunt through all the files. 

 

Once we see an isolated demo, we'll do our best to jump in and help with your GSAP-specific questions. 

Posted

Hi,

 

I'm unable to download the file in your latest post but it seems to be the same as in your initial post. Based on that I can't seem to reproduce any odd behaviour in the demo you posted 🤷‍♂️

 

The only advice I can give you is to NEVER animate the trigger element of a ScrollTrigger instance, right now you have this:

useGSAP(() => {
  gsap.to(box1.current, {
    scrollTrigger: {
      trigger: box1.current,
      pin: true,
      start: 'top top',
      end: '+=1500 bottom',
      scrub: 0.8,
      markers: true,
    },
  });
});

So you're basically animating the same element you're using as a trigger and also the same element that is being pinned by ScrollTrigger, that is a really bad idea and could leave to unexpected results, is far better to wrap that element around a different one, pin and use the parent element as the trigger and animate the element inside it, something like this:

<section id="item1" ref={box1}>
  <div className="content"></div>
</section>

Then:

useGSAP(() => {
  gsap.to(".content", {
    scrollTrigger: {
      trigger: box1.current,
      pin: true,
      start: 'top top',
      end: '+=1500 bottom',
      scrub: 0.8,
      markers: true,
    },
  });
}, {
  scope: box1
});

Hopefully this helps

Happy Tweening!

  • Like 1

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...