'React: loading two different images for mobile and desktop

Inside a React app, I need to load two different versions of the same image on mobile and desktop. Both images are long SVG files. For this I created an extra component called MySvgImage.js, which contains the code for both SVG files.

Now inside another component, where I want to render the image, I'm importing MySvgImage.js and render.

But how can I show one SVG image for mobile and the other for desktop? What would be a good approach?



Solution 1:[1]

you could use this npm package

install it using :

npm install react-responsive

an example of what you would do :

 
const Example = () => (
  <div>
    <h1>Device Test!</h1>
    <MediaQuery minDeviceWidth={1224} device={{ deviceWidth: 1600 }}>
      <img src="first image/>
    </MediaQuery>
    <MediaQuery minResolution='2dppx'>
      <img src="second image/>
    </MediaQuery>
  </div>
)

Solution 2:[2]

Old post, but for future visitors, you could try the Picture element. So your use-case would look something like this (using @media queries):

<picture>
    <!-- Desktop use-case -->
    <source srcset="/path/to/desktop.svg" media="(min-width: 1240px)">
    <!-- Mobile use case will be the default (could always swap them) -->
    <img src="/path/to/mobile.svg" alt="" />
</picture>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 oubaydos
Solution 2 Chris Serra