Hydration failed with react-responsive generate div

532 Views Asked by At

I am rendering two different sections on my page because on desktop it should be a slider, and on mobile all should scroll. I'm using react-responsive, and on mobile I'm getting an error (3 times the same), but not on desktop load. If I close the warning, I can see the mobile code, without issues, the console shows that screen was detected as mobile. So how come I get this error?

enter image description here

My code looks like this:


    const isMobile = useMediaQuery({ query: '(max-width: 768px)' });
      const handleMediaQueryChange = (matches) => {
        if (matches) {
         // console.log("MOBILE");
        } else {
         // console.log("DESKTOP");
        }
      };
      handleMediaQueryChange(isMobile);
      useEffect(() => {
        handleMediaQueryChange(isMobile);
      }, [isMobile]);

then inside the return (

      {!isMobile && (
          <>
            <swiper-container init="false" ref={swiperElRef}>
               <div className="swiper-slide">data</div>
               <div className="swiper-slide">data</div>
            </swiper-container> 
            [...]
     </>
        )}

          {isMobile && ( 
             <>
              <div className="images-wrapper">
                 <div className="swiper-slide">data</div>
                 <div className="swiper-slide">data</div>              
              </div>
            </>
          )}

Normally, instead of the div that I put inside, i have a . Inside each slice, I have a div . The slider is not initializing on mobile.

I tried to conditionally render that class but it doesn't work. If I could also have pointers on that...

  <>
 <motion.div ref={ref}
   className={`${!isMobile && 'swiper-slide'}`} style={{ opacity, position }} lazy="true">
1

There are 1 best solutions below

0
On

try using

 if (typeof window !== 'undefined') {
      return window.matchMedia(query).matches
 }
 return false

or use a different library like here