Next.js Discord

Discord Forum

Nextjs render different images based on device

Answered
Singapura posted this in #help-forum
Open in Discord
SingapuraOP
Hi guys, in my hero this is the implementation that I have for displaying a different image based on device:
"use client";
import CardComponent from "@/components/Card";
import { whyUsSection } from "@/lib/constants";
import { montserrat } from "../ui/fonts";
import Image from "next/image";
import { useMediaQuery } from "@react-hook/media-query";
import { cn } from "@/lib/utils";

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>
      <section className=" rounded-md px-6 mt-8 md:mt-36 font-semibold flex justify-start items-center flex-col ">
        <h2
          className={`${montserrat.className}p-8 md:text-5xl text-2xl font-normal text-center text-title-color my-8 md:my-14`}
        >
          Why Choose Pristine Panes
        </h2>
        <div className="w-11/12 md:h-[1px] h-[1px] bg-gray-500 md:mb-10"></div>
        <div className="grid grid-cols-1 md:grid-cols-1 lg:grid-cols-3 gap-2 md:gap-4 p-4 ">
          {whyUsSection.map((element) => (
            <CardComponent
              key={element.title}
              title={element.title}
              content={element.content}
              footer={element.footer}
              icon={element.icon}
            />
          ))}
        </div>
      </section>
    </section>
  );
};

export default Hero;

From what I understand this is wrong, because in initial load on mobile, the hero screen is getting loaded. Can someone advise
Answered by Singapura
Wrapped it in a native html <picture> element and displayed different image based on screensize using <source />
View full answer

1 Reply

SingapuraOP
Wrapped it in a native html <picture> element and displayed different image based on screensize using <source />
Answer