Karma
Karma

Reputation: 41

react native: importing a file with dynamic filename

In React Native: I would like to import a file using require at runtime. e.g. let mydata = require('../data/' + new Date().getFullYear().toString() + '.json');

Since I have more than a couple hundred json files it is not feasible to hard code all the files. in angular you can just use the above code and it works, but I think RN requires a static path. I am hoping there is an alternative way to do it. any help appreciated!!!

Upvotes: 2

Views: 511

Answers (1)

Kamron Jurayev
Kamron Jurayev

Reputation: 97

This is one of the problems i have encountered. As i have heard of, react's require()only uses static url not variables, that means that you have to do require('/path/file'). Here is my version of solution:

const images = {
    profile: {
        profile: require('./profile/profile.png'),
        comments: require('./profile/comments.png'),
    },
    image1: require('./image1.jpg'),
    image2: require('./image2.jpg'),
};
export default images;

not the best option, but you can get away with it sometimes.

Upvotes: 1

Related Questions