2

I'm currently trying to code something using the latest stable version of React.

I'm trying to load images in some react subcomponents by passing in the image urls are props, which I have originally stored in a JSON file. However, when I try to load the image by inputting, for example,

<img src={require(this.props.imageUrl)} />

I end up with the following error:

Error: Cannot find module "." webpackMissingModule

However, when I input the string that's stored within this.props.imageUrl into the require() function such as below:

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

The image loads perfectly fine. I've confirmed multiple times that the string is passed through properly to the this.props.imageUrl variable, but I always end up with the above mentioned error upon exchanging the typed string for the variable that stores it in the require() function.

Any insight or help would be greatly appreciated. Thank you.

MoSheikh
  • 769
  • 1
  • 11
  • 20
  • 1
    Webpack works by statically analyzing your code and looks for require statements. It doesn't interpolate variables. – Andy Ray Dec 22 '17 at 14:52
  • Thanks @AndyRay. Do you have any suggestions on how I can reapproach how I'm loading my images for display in the example I brought up? Thanks. – MoSheikh Dec 22 '17 at 15:06
  • If the images are a fixed number, you can create one component per image and then just import the correct component. If the images are dynamically loaded, just pass a URI, like : `` – Facundo La Rocca Dec 22 '17 at 17:32

0 Answers0