1

I am using the source of an image through a variable array. I tried the variable and with the backticks as well but it is giving me error that Error: Cannot find module '../../images/sectors/pellet-mill.png'. If I am using the source url only it works fine. Why can't we use the variable in require()??

<img
     className="card-img-top"
     src={require(`${data[0].image}`)}
     alt="pellet-mill"
/>```
4
  • By default require only handles js and json. Unless you have some special webpack loader for png files require won't work. Commented Sep 22, 2020 at 17:37
  • Try just `<img className="card-img-top" src={data[0].image} alt="pellet-mill" /> Commented Sep 22, 2020 at 17:39
  • 2nd option is import but it can't be used in this case. What else can we use? Commented Sep 22, 2020 at 17:40
  • Tried that already it didn't work Commented Sep 22, 2020 at 17:40

2 Answers 2

5

Webpack can only bundle resources that it can identify at bundle time. So how exactly is Webpack going to know what file require(data[0].image) represents? It can't, because that file path is only known at runtime, not bundle/compile time.

A different approach would be to require() (or better yet, import) all of the static image paths ahead of time in a dedicated JS file, and then use that as a "map" to the bundled images. Something like this:

// images.js
import image01 from './my/path/to/image01.jpg';
import image02 from './my/path/to/image02.jpg';

const images = {
  image01,
  image02
};

export default images;
// Some component file
import images from './images.js';

function MyComponent() {
  return <img src={images.image01} />;
}

The exact structure of images or your data is less important than the concept of importing the static assets ahead of time so that they get bundled, and then utilizing that structure at runtime to access the bundled assets.

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

3 Comments

actually I am using a json file in which I have all my data to print on the card component so that I don't need to repeat the component. There are other things as well not only the image so is there any way to handle that in js file?
@Sohaib I’m not sure what you mean. Can you post more info about the JSON file and structure of your project in your original question?
I figured a solution. Thanks alot brother that helped alot.
0

Ive had same problem and solved it in this way:

first need a function to return me the required part of src :

function ExtractImageName(address: string) {
    console.log(address.split("/").slice(-1));
    return address.split("/").slice(-1);
  }

then replace source with this :

 <img
     src={require(`../../assets/img/slider/${ExtractImageName(
     item.imageaddress)}`)}/>

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.