marzy
marzy

Reputation: 81

Reference an image based on props in react

I have a component that renders an image. The image will be different based on an api call and the data being returned.

Based on api call I will get a string such as the following:

{ assetName: 'company123' }

I would like to pass this prop down to the component which will then reference an image we have for that name.

/images/company123.png

<img src={'/images/${assetName}.png'} />

Typically I would just import the image and use it but this is not possible when I need to change the image based on the prop value.

How can I achieve the above?

Thanks, Lee

Upvotes: 3

Views: 488

Answers (1)

ArchNoob
ArchNoob

Reputation: 4126

I think you are mixing the quotations with backticks string concatenation and it should be the backticks instead.

<img src={`/images/${assetName}.png`} />

Note: This is called template literals. (Thanks, Chris).

More on template literals

Upvotes: 4

Related Questions