Jump to content
Search Community

implement observer plugin in react js

BhaskarG test
Moderator Tag

Recommended Posts

Hello,

I would like to convert the `Animated Continuous Sections with GSAP Observer` JavaScript code by Brian into a React.js component. However, I encountered the following error: `GSAP target undefined not found. https://greensock.com.` Could anyone assist me in converting the JavaScript code to React.js code?

Thank you in advance.
my code:
 

import React, { useLayoutEffect, useState, useRef } from "react";
import { gsap } from "gsap"
import { Observer } from "gsap/Observer";
import '../GCCarousel.css';

gsap.registerPlugin(Observer);

const GCCarousel = () => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const main = useRef()
  let animating = false;

  useLayoutEffect(() => {
    let ctx = gsap.context(() => {
    const sections = document.querySelectorAll("section");
    const images = document.querySelectorAll(".bg");
    const headings = gsap.utils.toArray(".section-heading");
    const outerWrappers = gsap.utils.toArray(".outer");
    const innerWrappers = gsap.utils.toArray(".inner");
    const wrap = gsap.utils.wrap(0, sections.length);

    gsap.set(outerWrappers, { yPercent: 100 });
    gsap.set(innerWrappers, { yPercent: -100 });

    function gotoSection(index, direction) {
      index = wrap(index); // make sure it's valid
      animating = true;
      let fromTop = direction === -1,
        dFactor = fromTop ? -1 : 1,
        tl = gsap.timeline({
          defaults: { duration: 1.25, ease: "power1.inOut" },
          onComplete: () => (animating = false),
        });
      if (currentIndex >= 0) {
        // The first time this function runs, current is -1
        gsap.set(sections[currentIndex], { zIndex: 0 });
        tl.to(images[currentIndex], { yPercent: -15 * dFactor }).set(sections[currentIndex], { autoAlpha: 0 });
      }
      gsap.set(sections[index], { autoAlpha: 1, zIndex: 1 });
      tl.fromTo(
        [outerWrappers[index], innerWrappers[index]],
        { yPercent: (i) => (i ? -100 * dFactor : 100 * dFactor) },
        { yPercent: 0 },
        0
      )
        .fromTo(images[index], { yPercent: 15 * dFactor }, { yPercent: 0 }, 0)
        .fromTo(
          headings[index].chars,
          { autoAlpha: 0, yPercent: 150 * dFactor },
          {
            autoAlpha: 1,
            yPercent: 0,
            duration: 1,
            ease: "power2",
            stagger: {
              each: 0.02,
              from: "random",
            },
          },
          0.2
        );

      setCurrentIndex(index);
    }

    const handleScroll = (event) => {
      if (!animating) {
        const direction = event.deltaY < 0 ? -1 : 1;
        gotoSection(currentIndex + direction, direction);
      }
    };

    document.addEventListener("wheel", handleScroll);
    document.addEventListener("touchstart", handleScroll);
    document.addEventListener("pointerdown", handleScroll);

    gotoSection(0, 1);

    return () => {
      document.removeEventListener("wheel", handleScroll);
      document.removeEventListener("touchstart", handleScroll);
      document.removeEventListener("pointerdown", handleScroll);
    };
    }, main); // <- IMPORTANT! Scopes selector text
        return () => ctx.revert();
  }, [currentIndex]);

  return (
    <main ref={main}>
      <header>
        <div>Animated Sections</div>
        <div>
          <a href="https://codepen.io/BrianCross/pen/PoWapLP">Original By Brian</a>
        </div>
      </header>
      <section className="first">
        <div className="outer">
          <div className="inner">
            <div className="bg one">
              <h2 className="section-heading">Scroll down</h2>
            </div>
          </div>
        </div>
      </section>
      <section className="second">
        <div className="outer">
          <div className="inner">
            <div className="bg">
              <h2 className="section-heading">Animated with GSAP</h2>
            </div>
          </div>
        </div>
      </section>
      <section className="third">
        <div className="outer">
          <div className="inner">
            <div className="bg">
              <h2 className="section-heading">GreenSock</h2>
            </div>
          </div>
        </div>
      </section>
      <section className="fourth">
        <div className="outer">
          <div className="inner">
            <div className="bg">
              <h2 className="section-heading">Animation platform</h2>
            </div>
          </div>
        </div>
      </section>
      <section className="fifth">
        <div className="outer">
          <div className="inner">
            <div className="bg">
              <h2 className="section-heading">Keep scrolling</h2>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
};

export default GCCarousel;

 

See the Pen OJaZbay?editors=0110 by Bhaskar-Guthula (@Bhaskar-Guthula) on CodePen

Link to comment
Share on other sites

It's pretty tough to troubleshoot without a minimal demo - the issue could be caused by CSS, markup, a third party library, your browser, an external script that's totally unrelated to GSAP, etc. Would you please provide a very simple CodePen or Stackblitz that demonstrates the issue? 

 

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

 

Here's a starter CodePen that loads all the plugins. Just click "fork" at the bottom right and make your minimal demo

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

 

If you're using something like React/Next/Vue/Nuxt or some other framework, you may find StackBlitz easier to use. We have a series of collections with different templates for you to get started on these different frameworks: React/Next/Vue/Nuxt.

 

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

  • Like 1
Link to comment
Share on other sites

Hello,

@GSAP Helper,  I am currently trying to convert GSAP JavaScript code to React GSAP code. However, I am feeling confused and unsure about the process. Can you please help me by converting the following code to React.js?

Your support will be greatly appreciated. Thank you in advance.

this is the code pen of GSAP JavaScript code to be converted to react:

See the Pen OJaZbay by Bhaskar-Guthula (@Bhaskar-Guthula) on CodePen

 

Link to comment
Share on other sites

Hi,

 

Unfortunately that is not the simplest thing to achieve since there are a lot of moving parts and converting HTML markup to JSX and make it work in React environments is not simple in terms that it can be a bit time consuming. We love helping our users, but unfortunately we don't have the time resources to create custom solutions for them,  like in this case porting an HTML VanillaJS example to React or any other framework.

 

Yesterday I added a few links in another thread you created. FreeCodeCamp's channel has a few videos of React courses not one year old, so they should be using up-to-date versions and APIs:

https://www.youtube.com/@freecodecamp/search?query=react

 

I strongly recommend you to invest some time in those in order to get a better grasp of how to create React apps.

 

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