reactjsjpegreact-bootstrapwebpfallback

How to display WEBP images with fallback to JPG images using react-bootstrap?


I am currently implementing a website using ReactJS and react-bootstrap.

I followed this Image Component usage, which enables me to display images in my website.

Now that I want to optimize the website by changing my images from JPG to WEBP (I will do the offline conversion myself and place all the images of two different extensions in the same folder). After that, I would like to display WEBP images to those visitors who can process it, and fallback to JPG images for those who can't.

I did some research but found some techniques like using picture tag that is not what I am using in my website (I am using react-bootstrap Image), or the use of Gatsby, which I am not familiar with.

The code I have now is something like this:

<Image src="my/local/path/image.jpg"/>

I just want to use fallback concept in this Image component. Is there any way to do it without complex customization? Additional third party library is acceptable.


Solution

  • According to the code posted with bootstrap document, it seems that the Image component internally outputs img while passing props and assigning needed classes to it, so I think the following example should work.

    I only tested it with webp disabled on Firefox, but here is a quick demo on: stackblitz.

    <picture>
      <source srcSet="imgurl/img.webp" type="image/webp" />
      <source srcSet="imgurl/img.jpg" type="image/jpeg" />
      <Image src="imgurl/img.jpg" alt="image" fluid rounded />
    </picture>
    

    The output of the above in HTML should be similar to:

    <picture>
      <source srcset="imgurl/img.webp" type="image/webp" />
      <source srcset="imgurl/img.jpg" type="image/jpeg" />
      <img src="imgurl/img.jpg" alt="image" class="img-fluid rounded" />
    </picture>