Search code examples
reactjsrequire

Require in reactjs is throwing cannot find module


Edit: Noob Helps here.

I checked a lot of similar questions already and none of them are quiet the same.

React is receiving an array of object from express. loop thru, get each object image link and add it to the source.

This is the original code

  {this.state.currentTemplates.map((items, pos) => {
            return (
              <div className={`template `}>
                <img src={require(`${items.link}1.jpg`)} />
                <p>{items.name}</p>
                <div className="buy">buy</div>
              </div>

if image exist like this, require will find it and it will work.

but if i send a request to another function to check if image exist first, like a try catch.

 <div className={`template `}>
//sending url to another function. Also I can put the function outside of class and just call without 'this' and it does not make any difference.

                <img src={this.checkUrl(`${items.link}1.jpg`)} />
                <p>{items.name}</p>
                <div className="buy">buy</div>

Ex:

 checkUrl(url) {
       console.log(url); // receive right url '../products/templates/a.jpg'
       try {  
 // try will require the right url but module cannot found it and it goes to catch. Now I can also put it in a variable var a= require(url) and it does not make a difference

          require(url);
console.log("it works "); // it never gets to here.
          return url; // this may not work once returned but it does not get to here.
      }catch(e) {
//react jump to catch with "cannot find module '../products/templates/a.jpg'"
         console.log(e);
       }
}

I got Error: require cannot find module '../products/templates/1.jpg'

interesting thing. If i add the product folder inside the component folder with the templates.jsx file. it works.

Also it is not a syntax error, i may have made a typo replicating the issue here.

Recap: if I call require(url) straight from the src jsx, it found image.

If i pass url to another function to do a try catch. Console log the right url but require throw cannot find module.

is this a react limitation? is there a work around ? am i approaching this thee wrong way ?


Solution

  • You are approaching it in the wrong way, your images MUST be served, not requiring it as a module. It must be included in your static assets, or an external url served in other server. This is the common pattern, please don't complicate it.

    If you have a public folder, just put it there like in the

    public/images/image1.jpeg
    

    Then in your code you can access it by:

    <img src="/images/image1.jpeg" />
    

    Provided you serve the assets.

    Hope this helps!