0

Currently, I have some code that is able to set a variable to be the same name as one of the import statements that call the images. I was trying to find a way to then use this to display the image. My code looks at some data and comes out with a name, say 'Bill', and assigns it to name. It would then try to show the image with the following code:

<img src={name} alt ='' />

instead of using

<img src={Bill} alt ='' />

I have an import statement at the top that is 'import Bill from path' and this is able to produce the bottom statement, but I would like for it to display with the variable. Let me know if this is too confusing so I can explain it better or you need more code and I could provide.

Added some better code:

import React from 'react'
import Bill from '../../img/players/Bill.jpg'
import Grant from '../../img/players/Grant.jpg'


const CharacterItem = ({ info, index }) => {
    var name = info[index][0].last_name
    console.log(name) //outputs Bill
    console.log(name === Bill) //outputs false
    return (
        <img src={'../../img/players/' + name} alt ='' />
goat 9009
  • 111
  • 1
  • 7

2 Answers2

1

The reason it's not working is because of the module bundler such as webpack which uses file-loader that outputs image files and returns paths when the images are imported.

Take a look at this https://webpack.js.org/guides/asset-management/#loading-images

<img /> tag src will refer to relative urls only if the path is for bundled static files in browser.

brijesh-pant
  • 967
  • 1
  • 8
  • 16
0

If you know the name of the file just provide the path as a string.

<img src={"./path/" + name} alt ='' />

If this doesn't solve your problem providing code or a better explanation can help.

Kyle DePace
  • 156
  • 7
  • I actually already tried this out and it didn't work. I added more code above and explained how some of the code outputted in the console as. If I take out the name and instead put Bill inside the quotes it doesn't work also so it only works when I type in just Bill without the full path. – goat 9009 Jul 26 '20 at 22:10
  • I tried '../../img/players/Armstrong.jpg' in src and '../../img/players/'+name+'.jpg' and both of them didn't work out. – goat 9009 Jul 26 '20 at 22:16
  • 1
    https://stackoverflow.com/a/34583854/10746985, 99% sure this is it then. – Kyle DePace Jul 26 '20 at 22:21