Jump to content
Search Community

scrollTrigger doesnt work with gsap.matchMedia() using Next.js

moosem1 test
Moderator Tag

Go to solution Solved by Rodrigo,

Recommended Posts

Hello, so im trying to use the matchmedia feature with ScrollTrigger in Next.js , the code runs perfectly when it's NOT inside the gsap matchmedia callback and starts it behaves strangely when it is. Below is a simple demostration referencing the main container and the target element to animate. Suggestions on why it's not working properly would greatly be appreciated. 

 

 if (typeof window !== "undefined") {
    gsap.registerPlugin(ScrollTrigger);
  }   

useEffect(() => {

let mm = gsap.matchMedia();

      mm.add("(min-width: 1080px)", () => { 
          const tl = gsap.timeline({ paused: false });
        
          const st = ScrollTrigger.create({
          trigger: containerRef.current,
          start: 'top top',
          end: `+=${containerRef.current.offsetHeight}`,
          pin: true,
          animation: tl,
          scrub: true,
          pinSpacing: true,
        });
        
        tl.to(textContainerRef.current, {y: -600,x: 0, duration:2 });
        
        return () => { 
           st.kill();
           tl.kill();
         };
      });
  }, []);

Thanks

Link to comment
Share on other sites

  • Solution

Hi @moosem1 and welcome to the GreenSock forums!

 

The cleanup section of the MatchMedia element is not the one you should use for cleanup in this particular setup, that has other uses that it might seem you don't need. Just revert the MatchMedia instance in the useEffect hook cleanup section and see how it goes:

const useIsomorphicLayoutEffect = typeof window !== "undefined" 
  ? useLayoutEffect 
  : useEffect;

gsap.registerPlugin(ScrollTrigger);

export default function Home () {
  useIsomorphicLayoutEffect(() => {
    const mm = gsap.matchMedia();
    mm.add(() => {});
    // React component cleanup, just revert GSAP MatchMedia
    return () => mm.revert();
  }, []);
  
  return (
    /* JSX */
  );
};

Hopefully this helps. If you keep having issues, please include a minimal demo in order to have a better look at what the issue could be. Here is a GSAP & ScrollTrigger starter template in NextJS that you can fork:
https://stackblitz.com/edit/nextjs-5cm4qn?file=pages%2Findex.js

 

Happy Tweening!

  • Like 3
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...