Reputation: 2198
I want to load some local images dynamically in my app. I have a json with records like
{name: image12, poster: 'image1.jpg'}, {name: image13, poster: 'image2.jpg'}
I have a folder with many images like 'image1.jpg', 'image2.jpg', 'image3.jpg'. When I try to render the json record i put
<img src={'./image/image1.jpg'}/>
but it is not working.
[![import React from 'react';
const Poster = (props) => {
return(
<div className="individual-poster">
<h2>{props.postData.name}</h2>
<img src={'./Slices/'+props.postData["poster"]} width="100px" height="100px"/>
</div>
);
}
image is not even listing in the source list also.
Upvotes: 1
Views: 2459
Reputation: 4957
If you created you react app with create-react-app then you can import image variable and later use it multiple time.
import logo from './logo.png' // relative path to image
class App extends Component {
render() {
return (
<img src={logo} alt={"logo"}/>
)
}
}
or you can directly specify image relative path.
<img src ="http://localhost:3000/img/foo.png" />
<img src="/details/img/bar.png" />
In your question for use images from array
const images = [{
name: 'image12',
path: 'image1.jpg'
}, {
name: 'image13',
path: 'image2.jpg'
}];
class App extends Component {
render() {
return (
<div>
<img src={logo} alt={"logo"}/>
{images.map((img) => <img src={img.post} alt={img.name} />)}
</div>
)
}
}
Upvotes: 0
Reputation: 3062
if you know path images then your json object you trying to map must be somewhat similar to this:
const obj = [
{"name":"Chrysanthemum","path":require('./Chrysanthemum.jpg')}, //this will work
{"name":"Desert","path":'./Desert.jpg'}, //will not work
]
require
your path to images must be inside require mehtod.
Use like considering json obj file exported as default in same directory with file name imagesJson
.
import imagArray from './images';
map like this
imagArray.map((m)=>{
return <div>
{m.name}
<img src={m.path}/>
</div>
})
Upvotes: 1