Next.js Discord

Discord Forum

Display different image based on device

Answered
Singapura posted this in #help-forum
Open in Discord
SingapuraOP
I have 2 hero images, one for desktop, one for mobile. And I need to display one or the other depending on the device.
This is how I have been doing it:
const Hero = () => {
  const isMobile = useMediaQuery("(max-width: 768px)");
  const aspectRatio = isMobile
    ? "aspect-[300/500]"
    : "aspect-[500/450] 2xl:aspect-[500/230] lg:aspect-[500/300] md:aspect-[500/350] ";

  return (
    <section className="w-full">
      <div
        className={cn(
          ` relative transition-transform ease-in-out duration-500 `,
          aspectRatio
        )}
      >
        <Image
          src={isMobile ? "/hero-mobile.jpg" : "/hero-blue.jpg"}
          alt="pristine panes hero"
          objectFit="cover"
          fill
          className="object-cover"
        />
      </div>

This does not work, it only works if I am on desktop and I resize to mobile. But on mobile initial load, the desktop hero image gets displayed.
I thought I had solved this using the <picture> element but then the aspect ratios would not work.

Thanks in advance
Answered by Rafael Almeida
have you tried using a custom srcset? this allows you to dynamically change the src of the image depending on the viewport: https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#resolution_switching_different_sizes
for the aspect ratio you would need to use media queries to avoid a flicker
View full answer

4 Replies

Answer
@Rafael Almeida have you tried using a custom `srcset`? this allows you to dynamically change the src of the image depending on the viewport: <https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#resolution_switching_different_sizes> for the aspect ratio you would need to use media queries to avoid a flicker
SingapuraOP
<picture>
          <source media="(max-width: 768px)" srcSet="/hero-mobile.jpg" />
          {/* Source for larger devices */}
          <source media="(min-width: 769px)" srcSet="/hero-blue.jpg" />
          <Image
            src={"/hero-blue.jpg"}
            alt="pristine panes hero"
            objectFit="cover"
            fill
            className="object-cover"
          />
        </picture>


I just did this, seems to work. And moved the aspect ratios in the className
yeah that works too
SingapuraOP
Thank you