Reputation: 365
I have a JSON response with a load of data such as an image location.
Then when I try to load the image React cannot find it.
None of the answers of similar questions help because they all tell me to import the image but I need to load it on the cuff. Eg:
{Object.values(this.state.advertisements).map((advertisement, i) => {
...
<img width='80px' src={require(advertisement.image)} alt='house'/>
Then I get an error 'cannot find module'.
The path looks like this:
image:
./images/house.JPG
,
Upvotes: 0
Views: 3173
Reputation: 10895
As mentioned in the comment, require
is used to include binary modules or other JS files. Rarely is it used to include actual data from images and such, when using it with webpack in the first place.
Depending on your returned data it is feasible to write <img src={advertisement.image} />
assuming that the data is well-defined and an actual link to an external image.
Upvotes: 2
Reputation: 4182
I think we don't need require.
src={`./images/${advertisement.image}`}
will work fine to import the image.
To be on safer side, you can add environment variables to store the server URLs and local URLs.
In production src={`${url}/images/${advertisement.image}`}
will load the image from the server.
Upvotes: 0