Sanke
Sanke

Reputation: 746

Load a set of images from a directory in React Native

I have a group of images in a directory and I want to add the paths to an array in react native.

The image names are 1.png, 2.png, 3.png... 20.png

The following is the method I currently use

 const images = [require('../assets/1/1.png'),
                 require('../assets/1/2.png'),
                 require('../assets/1/3.png'),
                 ...
                 require('../assets/1/20.png'),];

This is possible when there is a limited number of images. In some cases I might have to add 300 images. So is there an easy way to do this?

I tried adding in a loop but it does not work.

    for (let i = 1; i < 300; i++) {
        images.push(require('../assets/1/'+i+'.png'))    
    }

EDIT : The following error occurs in the above approach,

error: bundling failed: Error: Components\IdleLoop.js:Invalid call at line 9: require('../assets/1/' + i + '.png')
    at F:\_work\sampleApp\node_modules\metro\src\JSTransformer\worker.js:317:19
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (F:\_work\sampleApp\node_modules\metro\src\JSTransformer\worker.js:75:24)
    at _next (F:\_work\sampleApp\node_modules\metro\src\JSTransformer\worker.js:95:9)

Upvotes: 1

Views: 739

Answers (1)

Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34780

As far as I know because React Native applications are statically bundled on build time, required assets are linked in advanced therefore there isn't a way to load them dynamically on runtime. I've ran into the same problem and gave up on that and ended up linking everything manually/statically.

For more information you might want to check out React Native - Image Require Module using Dynamic Names, which concludes the same.

Upvotes: 1

Related Questions