1

I am trying to require multiple images from a folder within my react native project. I am trying to dynamically load the images I need to render an animation with a react-native-image-sequence component in another react component. I know you can only require images by only passing a string in react-native like this: require("../somepath"), so I am trying to find a work around to load multiple images by passing in a dynamic path. I need to be able to pass the image sequence component an array like this:

 [ require("./1.png"), 
   require("./2.png"), 
   require("./3.png")
 ]

for it to render the animation sequence.

I have tried creating a file that contains a method called prepareDirImages that creates and returns a string that contains an array full of require statements to the path passed in as well as the extension of the file. My plan was to then use this method in the component that I am creating and calling eval(prepareDirImages("./dirPath", "png")) to transform the string into its actual array representation and then passing this into the image sequence component.

prepareReactImages.js:

   module.exports = {
    prepareDirImages(path, ext){
        fs.readDir(path).then(files => {
            const ex =
            "[\n" +
            files.map((x, index) =>{
                if(index < result.length - 1){
                    return `require("${path}/${x}"),`
                }
                `require("${path}/${x}")`
            }).join("\n") +
            "]";
            console.log(ex)
          fs.writeFile("../images/index.js", ex);
          return ex;
        })   
    }

}

myComponent.js:

  import React, { Component } from 'react';
  import ImageSequence from 'react-native-image-sequence';
  import { prepareDirImages } from '../services/prepareReactImages';
  import { View, Text } from 'react-native';
  const fs = require('react-native-fs');


  export default class myComponent extends Component {

 render(){
   console.log(eval(prepareDirImages("../images/imagesDir", "png")))
   let images = getImages();

return (
  <View>
      <ImageSequence
              images={images}
              style={this.props.style} 
              framesPerSecond={24}
            />
  </View>

);
  }

}

   async function getImages(){
    return eval(await prepareDirImages("../images/ed_anim_wave_v01", 
    "png"))
   }

What I get is a promise and I get an error saying that imagesequence cant using property filter of object. I read that you have to use fs.MainBundlePath or fs.DocumentDirectoryPath but I dont understand how to get these files. If anyone can help me out, I'd appreciate it tremendously!!

  • As far as I am aware you cannot dynamically require files. https://stackoverflow.com/questions/30854232/react-native-image-require-module-using-dynamic-names – Andrew Jan 12 '19 at 21:21
  • Right. I also heard of a webpack solution which I tried but for some reason that didn't work either.. – Patrick Hammet Jan 13 '19 at 06:40

0 Answers0