Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 746
marzy Avatar asked Aug 29 '26 11:08

marzy


1 Answers

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

like image 67
ArchNoob Avatar answered Aug 31 '26 02:08

ArchNoob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!