Render images according to screen size

Hello!

I am trying to change my images depending on the size of the screen, but I have a problem and it is that I cannot get it to work correctly.

The problem is that when I first load the web it does not work correctly, but when I change the screen size manually with the Chrome tools it works.

I am attaching the code that I am using to see if someone can give me a hand.

  const [mobile, setMobile] = useState(typeof window !== "undefined" && window?.innerWidth);
  const breakpoint = 720;

  useEffect(() => {
    const handleWindowResize = () => setMobile(window.innerWidth);
    window.addEventListener("resize", handleWindowResize);
    
    // Return a function from the effect that removes the event listener
    return () => window.removeEventListener("resize", handleWindowResize);
  });

<img
    className="bannerHome__cont2-img1"
    src={ mobile > breakpoint ? imgBarcelona : imgBarcelonaMovil }
    alt="foto de manuel carrion"
    loading="lazy"
 />

I am a newbie to react and frontity, how could I solve this?

Thank you so much

Hi @manuwweb, I think you should check for srcset attribute for <img> tag.

In srcset attribute you can give all your multiple sizes images, and it will pick automatically.

Here is the Example

<img 
src="https://i0.wp.com/babacricnews.s3.ap-south-1.amazonaws.com/wp-content/uploads/2021/12/14150834/3-ODIs.jpg?fit=1280%2C720&amp;ssl=1" 
srcset="https://i0.wp.com/babacricnews.s3.ap-south-1.amazonaws.com/wp-content/uploads/2021/12/14150834/3-ODIs.jpg?fit=300%2C169&amp;ssl=1 300w, https://i0.wp.com/babacricnews.s3.ap-south-1.amazonaws.com/wp-content/uploads/2021/12/14150834/3-ODIs.jpg?fit=1024%2C576&amp;ssl=1 1024w, https://i0.wp.com/babacricnews.s3.ap-south-1.amazonaws.com/wp-content/uploads/2021/12/14150834/3-ODIs.jpg?resize=150%2C150&amp;ssl=1 150w, https://i0.wp.com/babacricnews.s3.ap-south-1.amazonaws.com/wp-content/uploads/2021/12/14150834/3-ODIs.jpg?fit=768%2C432&amp;ssl=1 768w, https://i0.wp.com/babacricnews.s3.ap-south-1.amazonaws.com/wp-content/uploads/2021/12/14150834/3-ODIs.jpg?resize=220%2C150&amp;ssl=1 220w, https://i0.wp.com/babacricnews.s3.ap-south-1.amazonaws.com/wp-content/uploads/2021/12/14150834/3-ODIs.jpg?resize=390%2C220&amp;ssl=1 390w, https://i0.wp.com/babacricnews.s3.ap-south-1.amazonaws.com/wp-content/uploads/2021/12/14150834/3-ODIs.jpg?resize=780%2C470&amp;ssl=1 780w, https://i0.wp.com/babacricnews.s3.ap-south-1.amazonaws.com/wp-content/uploads/2021/12/14150834/3-ODIs.jpg?resize=120%2C120&amp;ssl=1 120w, https://i0.wp.com/babacricnews.s3.ap-south-1.amazonaws.com/wp-content/uploads/2021/12/14150834/3-ODIs.jpg?fit=1280%2C720&amp;ssl=1 1280w">
1 Like

WOW

Thank you!