How i do i change img file for desktop and mobile view in react js?

Issue

I have two different img files one for desktop and one for mobile view but i don’t know how to put them both in my react code can anyone help?

As you can tell i’m new to react and this is what i know how to do so far…

import React from "react";
import House from "../images/mobile/house.jpg";
import HouseDesktop from "../images/desktop/house.jpg";


<img src={House} alt="house" />

Solution

You dont need react. just use pure HTML

<picture>
  <source media="(min-width:600px)" srcset={desktopimg}
  <img src={mobileimg} >
</picture>

details

The reason the code is not working. You can assign a single string to SRC. Not correct usage.

Methods for desktop-mobile img identification:
1)
Giving 2 different imgs and hiding one with CSS. so CSS does all the work.

  1. The new and practical solution is to use only the HTML picture tag.

It is better not to use java script as much as possible, then CSS.

Answered By – sawacrow

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published