Xen_mar
Xen_mar

Reputation: 9682

Responsive images with <picture> and <source> in ReactJS

I am trying to achieve HTML-"art direction" (displaying different images for different viewport widths) in React. This is the JSX:

import LogoImg from "../../abstracts/media/logo-large.svg";
import LogoImgMedium from "../../abstracts/media/logo-medium.svg";

<picture>
   <source srcSet={`${LogoImgMedium} 1x, ${LogoImg} 2x`} media="(max-width: 37.5em)" />
   <img 
      className="logo__apple" 
      srcSet={`${LogoImgMedium} 1x, ${LogoImg} 2x`} 
      alt="Full Logo"
      src={LogoImgMedium} />
 </picture>

The breakpoint defined in the media attribute does not seem to work. Do you guys know why? I have tried to specify it with px, rem and em.

Thanks.

Upvotes: 2

Views: 4189

Answers (1)

Maxime Launois
Maxime Launois

Reputation: 958

You just specified the same value in srcSet attributes of source and img elements, which will display the same image for all widths. This might vary, but the browser is more likely to select the medium image in that case.

To display medium image for small screens and large image, just change:

<picture>
   <source srcSet={`${LogoImgMedium} 1x, ${LogoImg} 2x`} media="(max-width: 37.5em)" />
   <img 
      className="logo__apple" 
      srcSet={`${LogoImgMedium} 1x, ${LogoImg} 2x`} 
      alt="Full Logo"
      src={LogoImgMedium} />
 </picture>

to:

<picture>
  <source srcSet={`${LogoImgMedium} 1x`} media="(max-width: 500px)" />
  <img
    className="logo__apple"
    srcSet={`${LogoImg} 2x`}
    alt="Full Logo" />
</picture>;

Upvotes: 5

Related Questions