How to give Image src dynamically in react js?

ghz 6months ago ⋅ 155 views

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?

Answers

It seems like you're on the right track with using dynamic values to set the image source (src). However, the issue might be related to how you're importing the images in your React component.

When you use require to import an image in React, Webpack will handle the import and bundle the image with your application. This works fine when the path to the image is known at compile time.

But when you want to dynamically set the image path using a variable, require won't work because it's a static import. Instead, you need to use a relative path to the image and make sure that the image exists at that location relative to your component file.

Here's the correct way to dynamically set the image path in your case:

<img src={`../img/${img.code}.jpg`} alt="Image" />

Make sure that img.code resolves to the correct image filename (without the .jpg extension) and that the image is located in the src/img directory relative to your component file.

If you're still encountering issues, double-check the file paths and ensure that the images are correctly named and located in the src/img directory. Additionally, verify that the img.code variable holds the correct values. If everything seems correct, you may need to provide more information about any error messages or unexpected behavior you're experiencing.