0

I hit another Problem with my project that I cannot resolve or understand.

 useEffect(() => {
axios.get(API_BASE_URL + '/user/images', payload)
    .then(function (response) {
        if (response.status >= 200 && response.status < 300) {
            console.log("RESPONSE IMAGE:" + JSON.stringify(response.data, null, 2));

            let files = response.data.files[0];
            const requirestring = "../../images/public/" + files;

            let requireimg;
            if(files == null){
               requireimg = require("../../images/basic-profile-picture.jpg");
            }else {
                try{
         >>           requireimg = require(requirestring);
                }catch (e){
                    requireimg = require("../../images/basic-profile-picture.jpg");
                }
            }
            setMapImages(<Image className={"profilepicture"} src={requireimg.default} alt={"TEXT"} />);
        } else {
            alert("error getting images");
        }
    })
    .catch(function (error) {
        console.log("DOWNLOAD: " + error);
    });

Why is this part:

  requireimg = require(requirestring);

throwing this exception:

Cannot find module '../../images/public/600bc441b2b2b62c542bd135_profilepicture.jpg'

But this works and isnt throwing an exception somehow:

 requireimg = require("../../images/public/600bc441b2b2b62c542bd135_profilepicture.jpg")

The exception first occurred when I set the image-name with an "_" for better syntax.

FunnyO
  • 383
  • 2
  • 20

1 Answers1

0

This happen because require is not a JavaScript API native function, is a Node function. So, when you try to run in browser, the browser can't recognize the require function with variable as argument.

See this stackoverflow link for more detailed information

Eddye Boy
  • 1
  • 1
  • Thanks. So how do I apply dynamic image-changes with variables in Javascript? – FunnyO Feb 10 '21 at 21:21
  • Follow this link, maybe can help you -> [StackOverFlow Link](https://stackoverflow.com/questions/45446879/dynamically-creating-image-link-jquery-or-vanilla-javascript/45452255) – Eddye Boy Feb 11 '21 at 18:52
  • In above link, look the pure js method do create an img dynamically, you can substitute the concatened method to Template Literal, cleaner and easy to use. – Eddye Boy Feb 11 '21 at 18:57