0

I have a folder structure like the one below:

Src
 Assets
   Images
 Components
   Information
     Lines

And I'm going to use all the photos in the image folder I tried the following method but got no answer:

let array = [];
for (let i=1 ; i < 21 ; i++) {
    array.push(
        <img src={require(`../../Assets/Images/Line${i}.JPG`)} alt=""/>
    )
}

I have twenty pictures with the following names:

Line1.JPG
Line2.JPG
.
.
.
Line20.JPG
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83

1 Answers1

0

In order to deal with this situation, we can use some third-party components. The first library is the babel-plugin-root-import, which allows us to import components using root-based paths.

Install

npm install babel-plugin-root-import --save-dev

Custom root

const rootImportOpts = {
  root: __dirname,
  rootPathPrefix: '~/',
  rootPathSuffix: 'src/js',
};
module.exports = {
  plugins: [['babel-plugin-root-import', rootImportOpts]],
};


babel.config.js


const rootImportOpts = {
      root: __dirname,
      rootPathPrefix: '~/',
      rootPathSuffix: 'src/Assets',
    };
    
        module.exports = (api) => {
          api.cache(true);
        
          const plugins = [['babel-plugin-root-import', rootImportOpts]];
        
          return { plugins };
        };

now you can use like this:

<img src={require(`~/your-image-name`)} alt=""/>

for more information you can visit babel-plugin-root-import github.

  1. This second we need to install is the react-app-rewired. This component allow us to change webpack configuration without using ‘eject’ and without creating a fork of the react-scripts