The problem I faced is with the img
tag. When a single image is concerned,
The below code loads the image:
import image1 from './images/image1.jpg';
<img src={image1} />
But the below code doesn't load:
<img src={'./images/image1.jpg'}/>
or
<img src='./images/image1.jpg'/>
I need to loop through json, something like:
[{'img':'./images/image1.jpg','name':'AAA'}, {'img':'./images/image2.jpg','name':'BBB'}]
Plus, display each of them as image with name as footer. Looping is fine but the images doesn't load. It is not actually possible for me to import every images to add. I don't use anything other than JSX as of now. Please favour.
Starting from React 17, JSX transform use special jsx function internally. You don't need to import it.
To display an image from a local path in React: Download the image and move it into your src directory. Import the image into your file, e.g. import MyImage from './thumbnail. webp' . Set the src prop of the image element to the imported image, e.g. <img src={MyImage} alt="horse" /> .
You need to require the file like so:
<img src={ require('./images/image1.jpg') } />
require
is used for static "imports", so you just need to change your imports
.
Example:
var imageName = require('./images/image1.jpg')
<img src={imageName} />
We could use require instead of import statment. Like ,
<img src={require("folder/image.format")} alt="image not found" />
But if you run it , it will show image not found!!!
We could simply solve it by changing the statment by adding .default
let image = require("folder/image.format");
<img src={image.default} alt="image not found" />
I just tried this, it works!
import I01d from '../../styles/images/01d.png';
....
<img src={this.getWeatherIconImage(iconCode)}/>
getWeatherIconImage(icon) {
switch (icon) {
case '01d': return I01d; ...
default: break;
}
}
The suggested answers do not appear to work any more. Here is a code fragment that highlight the issue.
import React from 'react';
import importImg from '../images/img.jpg';
export default function ImgTest(){
return(<>
<img src={importImg} alt='import'></img><br/>
<img src={require('../images/img.jpg')} alt='require function fails'></img><br/>
</>)
}
When this code is rendered, the following occurs.
1st displays the image - it the expected result
2nd displays the alt "require function fails" - is not the expected result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With