Render images according to screen size


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);

    src={ mobile > breakpoint ? imgBarcelona : imgBarcelonaMovil }
    alt="foto de manuel carrion"

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

srcset=";ssl=1 300w,;ssl=1 1024w,;ssl=1 150w,;ssl=1 768w,;ssl=1 220w,;ssl=1 390w,;ssl=1 780w,;ssl=1 120w,;ssl=1 1280w">
1 Like


Thank you!