Skip to content
Advertisement

GSAP Animations(TweenMax) not triggering in React,

I cannot figure out for the life me what how to get this Gsap animations to work. I’m still learning react but I was able to get everything to work properly in a standard project using html, css, and javascipt but i wanted to try and recreate the effect in React. There’s much more code, it’ll compile but the animations are kicking in. The error on the console says nothing is wrong and VSCode says nothing is wrong so i’m at a loss. Seems like it should be a simple fix though.

function App() {
  // Constants
    const leftContainer = document.querySelector('.left-container');

    if (leftContainer) {
        gsap.from(".left-container", {
            duration: 2,
            width: '0',
            ease: "power3.inOut",
        });
    }
    
    return (
        <>
<div className='containers'>
            <div className="left-container">
            </div>
</div>
        </>
    );
};

export default App;

However in a basic HTML it works when I write it as follows…

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.2/TweenMax.min.js"></script>
<script type="text/javascript">
      TweenMax.from(".left-container", 2, {
        width: "0",
        ease: Expo.easeInOut
      });

I also tried rewriting everything to follow the modern best practises.

Advertisement

Answer

In order to use gsap in react, make sure you have followed these steps:

  1. Create and run basic react app.
npx create-react-app my-app
cd my-app
npm start
  1. Install gsap in the react app using:
npm install gsap
  1. Import the gsap module into the app and use it with the useEffect hook.
import React, { useEffect, useRef } from "react";
import gsap from "gsap";
import "./App.css";

function App() {
  const appRef = useRef(); // create a ref for the root level element

  useEffect(() => {
    let ctx = gsap.context(() => {
      // normal selector text, automatically scoped to appRef 
      gsap.from(".left-container", {
        duration: 2,
        width: 0,
        ease: "power3.inOut",
      });
    }, appRef);

    return () => ctx.revert();
  });

  return (
    <>
      <div className="containers" ref={appRef}>
        <div className="left-container"></div>
      </div>
    </>
  );
}

export default App;

Here, React will re-run the useEffect() on every render. If you want to avoid that, add empty dependency array.

Like this:

useEffect(() => {

  // -- YOUR CODE --

}, []); // <- empty dependency array

Check this documentation for more info: greensock.com/react

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement