5

From this answer

Dynamically Add Images React Webpack

I know, how to use usual image src with React + Webpack.

How can I get the same result with srcset 2x having a space inside?

It looks like I can't import from a string like this:

import picture from './temp/picture@2x.jpg 2x';

It breaks, probably because of a space inside.

I tried to look for some plugin, but this

https://github.com/herrstucki/responsive-loader

clearly says that 2x is not supported.

And this

https://www.npmjs.com/package/srcset-loader

doesn't mention 2x at all, so I guess it doesn't support it too.

So, is there any way to use srcset 2x here?

Community
  • 1
  • 1

2 Answers2

11

Try this :

import LogoImg1x from 'YOUR_PATH/logo1x.png';
import LogoImg2x from 'YOUR_PATH/logo2x.png';

and

<img src={LogoImg1x} srcset={LogoImg1x + ' 1x,' + LogoImg2x + ' 2x'}/>
mlorber
  • 1,441
  • 1
  • 12
  • 20
  • 1
    This is great, but does it mean we're loading both images into the browser (even if we're not actually using them both)? If this is the case we'd be better off just loading the high res image and using that on low res devices. – Aidan Ewen Jul 14 '21 at 07:45
3

My solution: create helper function IsRetina(LogoImg1x, LogoImg2x)

export default function isRetina(first, second) {
  if (window.devicePixelRatio >= 2) {
    return second
  }
  return first;
};

Then use it anywhere like this

 <img src={isRetina(logo,logo2x)} />
Nikolai Novikov
  • 271
  • 1
  • 6