user4851524
user4851524

Reputation:

How to use srcset 2x with React and Webpack?

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/[email protected] 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?

Upvotes: 5

Views: 5354

Answers (2)

Nikolai Novikov
Nikolai Novikov

Reputation: 281

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)} />

Upvotes: 3

mlorber
mlorber

Reputation: 1541

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'}/>

Upvotes: 11

Related Questions