I am trying to give image name in src dynamically. I want to set image name dynamically using variable with path. but I am not able to set src correctly. I tried solutions on stackoverflow but nothing is working.
I tried to give path like this
<img src={`../img/${img.code}.jpg`}></img> <img src={'../img/' + img.code + '.jpg'}></img> <img src={'../img/{img.code}.jpg'}></img>
my images are saved in src/img path if i give path like this
<img src={require('../img/nokia.jpg')}/>
image is showing
I know this question is asked before but nothing is working for me. Please help me how can I set image path?
Use id into img tag and getElementById method then assign imager source to set image src in JavaScript. document.getElementById ('image').src = 'http://yourImagePathHere'; Also, one way to solve this is to use document.createElement and create your html img and set its. Example of JavaScript set image src dynamically
To add the image and display the image in reactjs, you need to first import the image from the images directory. To import the image in react component, just add the following line in your component.
If you used create-react-app, that would mean placing images in the public folder instead of the src folder. So if you had images in the public folder like: /public/articleImages/article2Image.png, you could use the url style attribute:
When setting a value to the src attribute, you can reference the variable name from the import statement. You can read more about import here. React developers use the require () method to load various types of modules.
if you dont want to require the image then you have to put all your images into public folder and then
<img src={`../img/${img.code}.jpg`}></img>
this method will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With