htmlimagenext.js

How to use next.js Image component with HTML <picture> element?


Next.js has an Image component that lazy loads images and also provides a srcset for a given image.

However, sometimes we want to deliver different images for different devices (art redirection).

Mozilla says we should use <picture> element for this purpose, providing different images for different media queries.

I can't find an article (even in next.js official docs) to tell us how can we do that using <Image> component.

Is it possible? How can I use next.js <Image> component and HTML <picture> element together?


Solution

  • I have searched for hundreds of websites, this is the only solution I found which workable on Next.js ( with tailwindcss ).

    import Image from 'next/image'
    
        <div>
          <div className="md:hidden">
            <Image src="Banner-767x500.webp" height={500} width={767} />
          </div>
          <div className="hidden md:inline-flex lg:hidden">
            <Image src="Banner-1023x500.webp" height={500} width={1023} />
          </div>
          <div className="hidden lg:inline-flex xl:hidden">
            <Image src="Banner-1400x500.webp" height={500} width={1400} />
          </div>
          <div className="hidden xl:inline-flex">
            <Image height={500} width={2000} src="Banner-2000x500.webp" />
          </div>
        </div>