I am using React and Node.js and I am trying to render images with the src attribute stored as a prop. But whenever I try to feed require()
a path stored as a variable it gives me this error: Cannot find module "."
So I am wondering why require cannot handle a variable that points to a path but can handle the path itself? For example, this will result in the error mentioned above:
<MyComponent imageSrc='./image.jpg'/>
...
<img src={require(this.props.imageSrc)}/>
But this will work perfectly:
<img src={require('./image.jpg')}/>
As explained in the comments actually you don't need to require any image here. You can use relative paths in your src directories. But, for your situation this will work:
Use require when you pass your prop to your component:
<MyComponent imageSrc={require("./image.jpg")} />
And use this prop there like:
<img src={this.props.imageSrc} />
An alternative solution I've learned recently:
<img src={require( "" + this.props.imageSrc) } />