Copy local files to documents folder

1.1k views Asked by At

sadly, RN are not capable to user string variables as parameter for require(). So, if you need to create a simple memory game 3x3 where each square you need to render a different image from the local folder: forget it.

I am trying to create a workaround for this: Copy files from my src/assets/*.** to the document folder. But it's not working.

My app is structured in this way:

/root folder
+---/android
+---/ios
+---/src
    +---/assets
           +----/x.png
           +----/y.png
    +---/index.js

on the index.js I've this line of code:

 RNFetchBlob.fs.cp("bundle-assets://../../assets/x.png", 
 RNFetchBlob.fs.dirs.DocumentDir +'/x.png')
            .then(() => { alert('done') })
            .catch((e) => { alert(e) })

I am using react-native-fetch-blob to copy the file so after copied I can use source={ uri: myFile } and load images dynamically.

Actually this code don't throw errors and create a zero-length file on the destination. Any clue ?

1

There are 1 answers

0
Danilo On

Well, you can't dynamically change the string in the require, but you can dynamically change the source of an image, I believe this would be an easier workaround for your situation. For instance, you can have requires selector set up for something like this:

let randomNumber = Math.floor((Math.random() * 10)/2);
let imageSource = null;
switch (randomNumber) {
    case 0:
        imageSource = require('./image1.jpg');
        break;
    case 1:
        imageSource = require('./image2.jpg');
        break;
    case 2:
        imageSource = require('./image3.jpg');
        break;
    case 3:
        imageSource = require('./image4.jpg');
        break;
    default:
        imageSource = require('./image5.jpg');
        break;
}

Then use that imageSource in your Image with:

<Image source={imageSource} />