Jump to content
Search Community

Gsap ScrollTo Plugin not working as expected (react)

Pariola-droid test
Moderator Tag

Recommended Posts

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

let indexToActivate = 0;

useEffect(() => {
    const startScrollSection = document.querySelector(".start-features-section");
    const scrollIndicator = scrollSectionIndicator.current;
    const featuredNodes = Array.from(document.querySelectorAll(".featured"));
    const featuredIndicators = Array.from(document.querySelectorAll(".features_section_indicator"));
    //
    const totalScrollableHeight = 3000;
    const sectionHeight = totalScrollableHeight / featuredNodes.length;

    console.log("sectionHeight", sectionHeight);

    gsap.set(scrollIndicator, {
      autoAlpha: 0,
      y: 100,
    });

    ScrollTrigger.create({
      trigger: startScrollSection,
      start: "top top",
      end: `+=${totalScrollableHeight}px`,
      scrub: true,
      pin: true,
      onUpdate: self => {
        console.log("self", self);
        console.log("prev", self.previous());
        // const scrollPosition = self.scroll() - self.start;
        const scrollPosition = totalScrollableHeight * self.progress;
        console.log("scrollPosition", scrollPosition);

        if (scrollPosition > 0 && scrollPosition < totalScrollableHeight) {
          gsap.to(scrollIndicator, {
            autoAlpha: 1,
            y: 0,
            transition: "ease-in-out-cubic",
          });
        } else {
          gsap.to(scrollIndicator, {
            autoAlpha: 0,
            y: 100,
            transition: "ease-in-out-cubic",
          });
        }

        indexToActivate = Math.floor(scrollPosition / sectionHeight);
        indexToActivate = Math.min(Math.max(indexToActivate, 0), featuredNodes.length - 1);
        console.log("indexToActivate", indexToActivate);
        //
        activateCurrentSection(indexToActivate);
      },
    });

    function activateNode(indexToActivate, nodeArray, className = "active") {
      if (indexToActivate >= 0 && indexToActivate < nodeArray.length) {
        nodeArray.forEach(_node => {
          _node.classList.remove(className);
        });
        nodeArray[indexToActivate].classList.add(className);
      } else {
        console.error("Index out of bounds:", indexToActivate);
      }
    }

    // button indicators
    function updateActiveFeatureIndicator() {
      activateNode(indexToActivate, featuredIndicators);
    }

    // scroll
    function updateActiveFeatureSection() {
      activateNode(indexToActivate, featuredNodes);
    }

    // parent function
    function activateCurrentSection(indexToActivate) {
      updateActiveFeatureSection(indexToActivate);
      updateActiveFeatureIndicator();
    }

      function scrollToCurrentSection(index) {
      indexToActivate = index;
      // activateCurrentSection(indexToActivate);
      gsap.to(startScrollSection, {
        duration: 1,
        scrollTo: {
          y: indexToActivate * sectionHeight,
          autoKill: false,
        },
        ease: "ease-in-out-cubic",
      });
    }
    // button click
    featuredIndicators.forEach((numberNode, index) => {
      numberNode.addEventListener("click", () => {
        scrollToCurrentSection(index);
      });
    });
  }, []);

Hello there, need help with a scrollTo issue, please
I'm trying to use a scrollTo plugin to scroll to a particular height in my pinned section (startScrollSection) when I click on my (featureIndicator) button and I also expect the scroll to continue from where I clicked correctly instead of starting from scrollPosition: 0
 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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. 

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