Skip to content
Advertisement

Can’t use a variable in require() in React

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"
/>```

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement