0

The task is simple: display a local image in a reactjs app based on dynamic data.

This is what I tried (assume path_to_image is derived dynamically):

<img src={require(path_to_image} />

generates an error:

Error: Cannot find module '../../images/logos/somelogo.jpg'

Without the require:

<img src={path_to_image} />

generates a broken image.

These two methods seem to be what people are doing, but no luck here. How do I solve this?

Eddy
  • 3,533
  • 13
  • 59
  • 89

3 Answers3

0
import image from "./path/to/image.png"

If you plan using more images in a dynamic way maybe you should store their paths in a db and then query the db for the respective path. Actually that's how it's done with a CMS for example. Even if you store the files on the same hosting, you would still save their paths to a DB instead of hardcoding.

0

Use this:

import SomeLogo from '../../images/logos/somelogo.jpg';

You can then use it like this:

<img src={SomeLogo} />

As for multiple images, you could store them in a JSON array, and then loop through them and add each image.

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
0

This does it:

let imageSrc = require("../../images/logos/generic.jpeg");
let dynamiclyGeneratedSrc = ...;
if (dynamiclyGeneratedSrc !== undefined) {
    imageSrc = require(`../../images/logos/${dynamiclyGeneratedSrc}`);
}
Eddy
  • 3,533
  • 13
  • 59
  • 89