Here is a simple and truly dynamic solution to the problem if you have a bigger no of files.
-Won't work for Expo Managed
Although the question is old I think this is the simpler solution and might be helpful. But I beg a pardon for any terminological mistakes, correct me please if I do any.
INSTEAD OF USING REQUIRE WE CAN USE THE URI WITH NATIVE APP ASSETS FOR ANDROID (AND/OR iOS). HERE WE WILL DISCUSS ABOUT ANDROID ONLY
URI can easily be manipulated as per the requirement but normally it's used for network/remote assets only but works for local and native assets too. Whereas require can not be used for dynamic file names and dirs
STEPS
- Open
android/app/src/main/assets
folder from your App.js
or index.js
containing directory, if the assets
folder doesn't exist create one.
- Make a folder named
images
or any NAME
of your choice inside assets
, and paste all the images there.
- Create a file named
react-native.config.js
in the main app folder containing App.js
or index.js
.
- Add these lines to the new js file:
module.exports = {
project: {
ios: {},
android: {},
},
assets: ['./assets/YOUR_FOLDER_NAME/'],
};
at the place of YOUR_FOLDER_NAME
use the newly created folder's name images
or any given NAME
- Now run
npx react-native link
in your terminal from main app folder, this will link/add the assets folder in the android bundle. Then rebuild the debug app.
- From now on you can access all the files from inside
android/app/src/main/assets
in your react-native app.
For example:
<Image
style={styles.ImageStyle}
source={{ uri: 'asset:/YOUR_FOLDER_NAME/img' + Math.floor(Math.random() * 100) + '.png' }}
/>