-1

In a react App, I would like to store the image path or at least the name of the image file in DB. The image source would be dynamically added.

The below code works:

<img src={require("../Images/amazon.jpg")}></img>

The below code does not work (error:Cannot find module '../Images/amazon.jpg'):

const path = `../Images/amazon.jpg`;
<img src={require( `${path}`)}></img>

How can we set the img src dynamically after fetching image path/name from database.

Joy
  • 105
  • 1
  • 2
  • 10
  • Does this answer your question? [React won't load local images](https://stackoverflow.com/questions/34582405/react-wont-load-local-imagest) – Liam Apr 08 '22 at 10:18
  • Specifically [this answer](https://stackoverflow.com/a/52195146/542251) – Liam Apr 08 '22 at 10:20

2 Answers2

0

If you have a public folder for assets, then you can try:

<img src={`../Images/amazon.jpg`}></img>
StepUp
  • 36,391
  • 15
  • 88
  • 148
-1

The best way is to just load your images from the URL.

<img src={url}></img>
zerob4wl
  • 69
  • 7
  • If the image isn't bundled this won't make any difference. – Liam Apr 08 '22 at 10:18
  • Usually, build tools like webpack and others don't bundle your image, they just read your require argument and move the image from that path to your build path, and fix the URL to a relative path. The important thing is, the require is working in your dev time not in runtime, and it means if you want to have it in runtime, you should use the URL string or related path string as src. – zerob4wl Apr 08 '22 at 10:23
  • *The image source would be dynamically added* – Liam Apr 08 '22 at 10:24