Search code examples
javascriptreactjsnext.jsserver-side-rendering

Conditionally Render Image on Server in Next.js


I feel like I already know the answer to this, but just wanted to see if anyone had a solution for this.

I have a hero banner where I have one image I want to show on mobile, but there's another I want to show on desktop.

Usually I would just conditionally render it, but then I get that weird flicker where the image first loads something by default and then switches to the right one.

Is there another way to deal with this?

Thank you!


Solution

  • I decided to use media queries to see if that would render on the server first and it seems to be doing what I want to be doing!

        <>
          <Image
            height={800}
            width={800}
            className="w-full max-lg:min-h-[515px] max-lg:scale-[1]  lg:hidden"
            src={heroMobile.src}
            alt="hero"
          />
          <Image
            height={1600}
            width={1600}
            className="hidden lg:flex"
            src={hero.src}
            alt="hero"
          />
        </>
    

    But if anyone else has another solution please still share.

    Edit: Sorry I had posted this before refreshing and saw there were answers.