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" />
CodePudding user response:
You dont need react. just use pure HTML
<picture>
<source media="(min-width:600px)" srcset={desktopimg}
<img src={mobileimg} >
</picture>
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.
- 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.
CodePudding user response:
You can get the width of current device and based on that screen width
you can change your img source.
<img src={window.innerWidth > 1024 ? HouseDesktop : HouseMobile} alt="house" />
CodePudding user response:
I suggest you this library: react-device-detect (https://www.npmjs.com/package/react-device-detect).
Than call the isMobile method to check the device and then render your image:
import {isMobile} from 'react-device-detect';
//If isMobile will render House otherwise HouseDesktop
<img src={isMobile? House: HouseDesktop} alt="house" />