Raphael G.
Raphael G.

Reputation: 1

React | Can´t load Images > Module not found

I have a problem in react, I can´t display my local pictures when the URL is stored in a variable, in my case i´m using the Array.Map function.

So the thing is I want to build a webapp to manage products, for every product there is a picture so I can´t import every single picture by myself.

So a product object looks like this:

products: {
 name: "Beer",
 beschreibung: "Gutes Bier",
 preis: 4,
 imgUrl: "./pics/Beer.png",
},

In my "Product.js" I mapping throw the product objects:

products.map(function (e, i) {
  return (
    <div className="container">
        <p>{e.name}</p>
         ...
        <img src="..."></img>
    </div>

so and here im trying several things:

//this works fine:
<img className="img" alt="hallo" src={require("./pics/Beer.png")} />


//this don´t work:
<img className="img" alt="hallo" src={require( `${e.imgUrl}` )} />

I checked the correct path so it is not a wrong URL. My project tree in /src is like this:

 -src
   -components
      #App.js
   -style
      #Style.css
   -data
      #Products.json   // There are my test-products saved
  -images
      #img1.jpg
      #img2.jpg
      ...

i figured out that when i place files direct inside the /src folder except the images folder then the map.function works fine, so i realy don´t know what to do here.

Upvotes: 0

Views: 1483

Answers (2)

Shivam
Shivam

Reputation: 3131

In case you need to pass the image as prop or use it in different places, you can store it in a variable(rather than rewriting require statement) and use it every where. If you are bundeling your modules using webpack. Because Beer.png is not a valid javascript module. Webpack will do the trick for you.

ES6 syntax

import beerImage from './pics/Beer.png'; //webpack handles it no need of transpiling

ES5 syntax

var beerImage = require("./pics/Beer.png")

products: {
 name: "Beer",
 beschreibung: "Gutes Bier",
 preis: 4,
 imgUrl: beerImage,
}

Upvotes: 1

jered
jered

Reputation: 11581

Why not just require() the images directly in the products data?

products: {
 name: "Beer",
 beschreibung: "Gutes Bier",
 preis: 4,
 imgUrl: require("./pics/Beer.png"),
}

Assuming you're bundling your product data with everything else, do that for every imgUrl and it should work fine. Your other option is to use something like the copy-webpack-plugin to copy your static files over and reference them with a normal, relative path URL.

Upvotes: 2

Related Questions