'How to Show Different Sized Image on Mobile in Next.js

I want to do something that I thought would be extremely simple: show an image at 200px x 200px, unless the screen size is < 500px, in which case show it at 100px x 100px instead.

This seems like the most basic responsive design one could have: just one image, with two different dimensions based on screen size ... but it seems impossible just using Next's <Image> tag. That tag has tons of related props (sizes, loader, srcSet ... plus the deviceSizes and imageSizes in the Next config) ... but none of them seem to let me achieve this basic goal.

I eventually got things working by:

  1. starting with an Image that uses layout="fill" and objectFit="cover"

  2. wrapping it with a <div> that has max-width and max-height (and min-width/height also) of 200px

  3. adding a media query to change the styles in #2 to 100px below 500px screen width

... but this feels like I'm just throwing out all of the power of the <Image> and rewriting my own component, and I don't get Next to automatically resize my images this way.

Is there any simpler way to get the same effect (again, same image, just two different dimensions, controlled by screen size) using the <Image> tag directly (and not just styling the <div> around it)?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source