Jump to content
Search Community

I can't handle media queries in react. Can you tell me where I'm doing wrong?

Semih test
Moderator Tag

Recommended Posts

Hi,

 

You have a couple of errors in your code.

 

The first one is that GSAP MatchMedia is actually an instance of GSAP Context with more capabilities, so reverting the MatchMedia instance is enough, no need to create a GSAP Context instance in your code like this:

let mm = gsap.matchMedia();
mm.add('(min-width: 800px)', () => {
  let ctx = gsap.context(() => {
    ...
  });

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

But that is just some unnecessary code, that's it. The real problem is this:

useLayoutEffect(() => {
  gsap.registerPlugin(ScrollTrigger);
  let mm = gsap.matchMedia();
  mm.add('(min-width: 800px)', () => {
    ...
  });
  mm.revert();
});

Basically you are reverting your MatchMedia instance as soon as you create it, so nothing happens regardless of the screen size. The cleanup phase on an effect hook is a function that is returned, like this:

useLayoutEffect(() => {
  gsap.registerPlugin(ScrollTrigger);
  let mm = gsap.matchMedia();
  mm.add('(min-width: 800px)', () => {
    ...
  });
  return () => mm.revert();
});

In order to correctly grasp this concept read more regarding useEffect and useLayoutEffect hooks:

https://react.dev/reference/react/useEffect

https://react.dev/reference/react/useLayoutEffect

https://react.dev/learn/synchronizing-with-effects#step-3-add-cleanup-if-needed

 

Hopefully this helps.

Happy Tweening!

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