Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give Image src dynamically in react js?

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?

like image 421
Vinay Avatar asked Jan 04 '19 06:01

Vinay


People also ask

How to set image SRC dynamically in JavaScript?

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

How to display an image in ReactJS?

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.

How do I put images in the public folder in react?

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:

How to set a value to the src attribute in react?

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.


1 Answers

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.

like image 128
Vikas Singh Avatar answered Sep 17 '22 15:09

Vikas Singh