Jump to content
Search Community

GSAP matchMedia crashing my code

TaiwoJazz test
Moderator Tag

Recommended Posts

Not sure what I'm doing wrong here but this code is causing other components not to render properly on mobile unless reload.

The matchMedia works but renders only once and doesn't re-render again even when I moved the mm constant out of the effect function and specify mm as a dependency in the useEffect.
 

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

const mouseHoverHandler = (index) => {
    const tween = tls.current[index];
    tween.reversed(!tween.reversed());
  };

  useIsomorphicLayoutEffect(() => {
    const mm = gsap.matchMedia();
    let ctx;

    mm.add('(min-width: 768px)', () => {
      ctx = gsap.context(() => {
        const cards = gsap.utils.toArray('.box');
        cards.forEach((card) => {
          const q = gsap.utils.selector(card);
          const tl = gsap
            .timeline({
              defaults: { duration: 0.5, autoAlpha: 1, ease: 'power1.inOut' },
            })
            .to(q('.box div'), {
              opacity: 1,
              scale: 1,
              transformOrigin: 'center center',
            })
            .from(
              q('.box p'),
              {
                opacity: 0,
              },
              '<'
            )
            .reverse();
          tls.current.push(tl);
        });
      }, dashboard);
    });

    return () => {
      mm.revert();
      ctx.revert();
    };
  }, []);


 

Link to comment
Share on other sites

Hi,

 

Please try to provide  minimal demo so we can take a look at it. In the link you'll find links for starter templates for React and NextJS.

 

Also there is no need to create a MatchMedia and a GSAP Context instance, Match Media is a wrapper for GSAP Context so you only have to create the Match Media instance and pass the scope to the add() callback:

useIsomorphicLayoutEffect(() => {
  const mm = gsap.matchMedia();
  mm.add(() => {}, myRef);// <- Scope!
  
  return () => mm.revert();
}, []);

Hopefully this makes things clearer. If you keep having issues please include a demo.

 

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