Reputation: 292
In a render (returned from a function), I have:
{console.log(property.image)}
{console.log(typeof property.image)}
<Image src={require('./images/0.jpg')} fluid rounded />
Which renders the image correctly and console logs "./images/0.jpg" string
But when I try:
{console.log(property.image)}
{console.log(typeof property.image)}
<Image src={require(property.image)} fluid rounded />
I get:
Error: Cannot find module './images/0.jpg',
which doesn't make sense to me...
Also, I am unsure how to assign variables in render, I tried :
{ var abc = property.image }
but get:
./src/App.js Syntax error: Unexpected token (220:12)
If someone can help me understand why, I would greatly appreciate it.
Upvotes: 0
Views: 34
Reputation: 3230
I'm assuming you are using web pack or something similar (create react app or parcel, for instance). That's (usually) where the require function comes from, and why you can 'require' an image. But the only images you can require are local ones (images in your project source), not images on the web.
If you want to get an image from the web, require is not what you want. In that case, you just pass the url as a string to the src
property.
However, if you do need images that are in your project source, then you would probably use require. Most of the time, you use require at the top of a file, and pass it a string, not a variable. This is because your packager reads the file before packing it up, and looks for any requires, so that it can include them in the package. But when you pass require a variable, it can't do that. However, you can use require.context
if you want to load files dynamically from a directory.
So you probably want this at the top of your file:
const pathToImages require.context('./images', true);
and in your render:
<Image src={pathToImages('0.jpg')} fluid rounded />
or
<Image src={pathToImages(property.image)} fluid rounded />
Upvotes: 1