0

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,

5
  • 1
    require is a directive to load a module such as JS files. Rarely is it used to include other formats such as images. How is your image data stored? As actual URLs to an external server or encoded data? If it's the former you can just use src={advertisement.image} assuming your data is well-defined. Commented Jan 12, 2019 at 22:19
  • Good point I am being stupid. Currently because I am developing I was testing with local images. Realistically the images will be on a Node server so I can just call the direct path. Cheers. Commented Jan 12, 2019 at 22:20
  • As a sidenote, keep in mind that your img elements should have unique key props to help React with rendering. Commented Jan 12, 2019 at 22:21
  • The parent div of the image has a key. That is enough right? Commented Jan 12, 2019 at 22:23
  • Basically the root element that you map onto should have a unique key. So if you map your images onto divs (with keys) that store the images you should be indeed fine, yes. Commented Jan 12, 2019 at 22:24

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.