Ruan
Ruan

Reputation: 4293

Reactjs require image url in variable is not working

Strange problem

I'm dynamically including the path to an image in the source directory.

Putting the image directory in as a string works Fine (the part I commented out), but as soon as I put it in a variable it gives me the error " Cannot find module ".""

   var imageDir="assets/img/MyImage.png";
  --Working     // const imageData= require('assets/img/MyImage.png');
  --Not Working    const imageData= require(imageDir);

Any one know why?

Same-ish problem Here No answer unfortunately

Upvotes: 4

Views: 2104

Answers (2)

Carr
Carr

Reputation: 2771

Webpack needs to know what files to bundle during compile-time, but the real path value for expression(variable) only be given in runtime, you need require.context:

/* If the structure is like:

    src -
         |
          -- index.js (where these codes are deployed)
         |
          -- assets - 
                     |
                      --img
*/  

      
let assetsPath = require.context('./assets/img', false, /\.(png|jpe?g|svg)$/); 

// See where are the images after bundling.
// console.log(assetsPath('./MyImage.png'));

// You can put all the images you want in './assets/img', and access it. 
var newElement = {
    "id": doc.id,
    "background": assetsPath('./MyImage.png');
};

Upvotes: 6

Miodrag Trajanovic
Miodrag Trajanovic

Reputation: 134

If you wish use image on your react web application you can use next code

when use directly in html tag, but if you can use in part of java script, you must use const image = require('../Assets/image/03.jpg') and call letter this constant like this {image} between example tags

Upvotes: 0

Related Questions