skip to Main Content

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


  1. 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:

    {
        list.map(item => (      
            <li key={item.id}>
                <img src={require(`../images/Image${item.id}.jpg`)}
     alt="" />
            </li>
            )
        )
    }
    
    Login or Signup to reply.
  2. 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

    <img src={`../images/${item.id}.jpg`} alt="" />
    

    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.

    import image1001 from '../images/1001.jpg';
    import image1002 from '../images/1002.jpg';
    import image1003 from '../images/1003.jpg';
    
    export const allImages = {
      image1001, // shorthand for image1001: image1001,
      image1002,                     
      image1003,
    };
    

    Usage:

    <img src={allImages[`image${item.id}`]} alt="" />
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search