Jump to content
Search Community

Horizontal Scroll randomly translating to the y direction when using typescript react

ajk test
Moderator Tag

Recommended Posts

So I was trying to create minimal page that horizontally when scrolled vertically. To implement these I have used an implementation from https://codesandbox.io/p/sandbox/nervous-pasteur-rws9rp?file=%2Fsrc%2FApp.js%3A82%2C7 which works fine in react js. However, when I try the exact same code in tsx, which you can find here https://codesandbox.io/p/sandbox/vigilant-cookies-6php56?file=%2Fsrc%2FApp.tsx it suddenly started to randomly translate the container to the y direction when scrolled slightly. I have tried many thing but was never lucky to solve the issue 

Link to comment
Share on other sites

Hi @ajk and welcome to the GSAP Forums!

 

First 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/

 

Finally in the case of your TSX demo, the different is that you're using snapping in your ScrollTrigger config, while in your JS demo you're not:

scrollTrigger: {
  trigger: descContRef.current,
  pin: true,
  scrub: 1,
  snap: 1 / (totalPanels - 1),// Here
  // base vertical scrolling on how wide the container is so it feels more natural.
  end: () => `+=${descContRef.current?.offsetWidth}px`,
},

If you remove that line, most likely this will work the way you intend.

 

Hopefully this helps.

Happy Tweening!

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