React - pixel ratio - set 2x 3x images for retina devices

2.6k Views Asked by At

I am creating a react app. I want the browser to server an image (twice bigger in resolution) to retina devices.

I am trying with 2x. I am trying in different ways:

The png is imported. {retina} is the URL of the twice bigger image. {logo} is the normal size image.

I have tried to implement it this way:

<picture>
<source srcset={`${retina} 2x, ${logo} 1x`} />
<img src={logo} alt="Flowers" />
</picture>

also this way:

<img srcset={`
${ratina} 2x,
${Logo} 1x,
`}
src={Logo}
></img>

and this way:

<picture>
<img src={logo} srcset={`${retina} 2x`} />
</picture> 

and this way:

<img src={logo} srcset={`${retina} 2x`} />

For testing purposes I gave the retina png image a different color, just to notice it immediately when it works.

Problem 1: In some of the above cases it shows twice the normal image, sometimes twice the retina images, but in none of the above cases it shows a normal image for 1x and 2x for retina devices. I am testing it on PC, iPhone, and with Chrome emulator with custom device set to pixel ratio 2.

Problem 2 (that's not really a problem, but...): In all cases the images are loaded in the browser as:

Can

  1. anybody point out what I am doing wrong so that the 2x image is not showing up?
  2. How can I import the image, so that the real image URL will be rendered and not a base64 without the need to create a .env file and set the IMAGE_INLINE_SIZE_LIMIT to 0? Any other way to achieve the same?

Thank you

1

There are 1 best solutions below

0
Shawn Clary On

Almost there. You just need to name the attribute according to JSX style, which is srcSet. Also, whatever you put in src is considered the default resolution load, so in srcSet you just need the 2x and 3x, if applicable.

Full Code Example using an image called logo:

import logo from '../path-to/logo.png'
import logo2x from '../path-to/[email protected]'
import logo3x from '../path-to/[email protected]'

<img
  src={logo}
  srcSet={`${logo2x} 2x, ${logo3x} 3x`}
/>