Jump to content
Search Community

Resizing doesnt work in react

Imran A test
Moderator Tag

Go to solution Solved by Rodrigo,

Recommended Posts

Hello Everyone ,

Recently i have started using React with GSAP, i have been creating a react app and i was able to achieve the animations but resizing doesn't happen and the container inside gets resized only when the page gets a reload and below is my demo code that illustrates the problem

Thanks in advance for help!
https://stackblitz.com/edit/gsap-react-basic-f48716-oddg3v?file=src%2Fhome.js
https://gsap-react-basic-f4871image.thumb.png.15fe04d72967056f33766a4562a7c071.png

See the Pen by (@) on CodePen

Link to comment
Share on other sites

  • Solution

Hi @Imran A and welcome to the GSAP forums!

 

The main reason for the issue is that you are not using GSAP Context:

https://gsap.com/docs/v3/GSAP/gsap.context()

 

When working with React and React environments (Next, Gatsby, etc), always use GSAP Context. Proper animation 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.

In GSAP 3.11, we introduced a new gsap.context() feature that helps make animation cleanup a breeze. All you need to do is wrap your code in a context call. All GSAP animations and ScrollTriggers created within the function get collected up in that context so that you can easily revert() ALL of them at once.

Here's the structure:

// typically it's best to useLayoutEffect() instead of useEffect() to have React render the initial state properly from the very start.
useLayoutEffect(() => {
  let ctx = gsap.context(() => {
    // all your GSAP animation code here
  });
  return () => ctx.revert(); // <- cleanup!
}, []);

This pattern follows React's best practices, and one of the React team members chimed in here if you'd like more background.

 

Here is a fork of your demo:

https://stackblitz.com/edit/gsap-react-basic-f48716-ztn5zt?file=src%2Fhome.js

 

Finally I strongly suggest you to go through our GSAP & React resources to learn more about correctly using GSAP in React projects:

https://gsap.com/resources/React/

 

Hopefully this helps.

Happy Tweening!

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