Reputation: 133
I am trying to load images based on the value here (Using React and JavaScript). Let me show you what I've currently got.
this.state.categories.map((value, index) => {
return <div className={categoryStyle.column}
key={index}
onClick={() => {this.setCategory(value)}}>
<img src={this.getImage(value)}/>
</div>
}) : <Spinner/> }
getImage = (category) => {
switch(category) {
case "people":
return "./img/people.png"
case "planets":
return "./img/planets.png"
case "films":
return "./img/films.png"
case "species":
return "./img/species.png"
case "vehicles":
return "./img/vehicles.png"
case "starships":
return "./img/starships.png"
default:
return console.log("No image available")
}
}
The value contains the category names, such as people or films. When I check in my Html the image src actually shows the /img/people.png, but the image is not loading.
What am I doing wrong here? Also, is there a more recommended way of doing this more dynamically?
Upvotes: 1
Views: 54
Reputation: 133
My issue here was that my images were in the src/img folder. I placed my images folder in the public folder now and everything works now!
I have also removed my function and just did the following.
<img height="50" src={"./categoryImages/" + value + ".png"}/>
Upvotes: 0
Reputation: 41893
You could add a require
inside src
prop:
<img src={require(this.getImage(value))} />
However I would suggest you to replace your switch
function with simple if else (require may not evaluate your console.log
properly).
Upvotes: 1