The following code imports and displays an image Image1001
.
import Image1001 from '../images/1001.jpg';
<img src={Image1001} alt="" />
The above code displays the image correctly. However I want to generate the image names dynamically. For example, 1001 is the ID that I get in the map function. So I am trying following {Image${item.id}
} but it does not display the image. Here is the full code:
{
list.map(item => (
<li key={item.id}>
<img src={`Image${item.id}`} alt="" />
</li>
)
)
}
I can see the following in the page source:
<img src="Image1001" alt="">
I think the problem is that it is adding "", that’s why it is not working.
I have also tried following:
<img src={'Image' + item.id} alt="" />
It also gives same result.
So my question is, how to create dynamic Image names.
2
Answers
Not sure it’s best practice, but you don’t actually need to import the image to use it, you should be able to do something like this, using
require
and the path to the image:Just a note: To the JS interpreter,
Image1001
is not a string, it’s a variable. Passing the string"Image1001"
is not the same as passing the variable.If the source file paths are consistent you can just put the path to the jpg directly
You probably want to use a path relative to the root instead of the current file though in case this file gets moved. ie. start with
/
instead of../
and give the path relative to the root directory.See here for syntax: https://www.w3schools.com/html/html_filepaths.asp
Otherwise you can create a resource file and export an object that has strings as keys, and the images as values. That will let you index the object with strings.
Usage:
This is better if the image file paths are subject to change, since IDEs can generally auto update those import statements. But it requires a lot more setup to add images.