React Native: require() with Dynamic String?

Jake Chasan picture Jake Chasan · Jul 9, 2017 · Viewed 25k times · Source

I have read several posts about issues that people are having with React Native and the require() function when trying to require a dynamic resource such as:

Dynamic (fails):

urlName = "sampleData.json";
data = require('../' + urlName);

vs. Static (succeeds):

data = require('../sampleData.json');

I have read on some threads that this is a bug in React Native and in others that this is a feature.

Is there a new way to require a dynamic resource within a function?

Related Posts (all fairly old in React time):

Answer

klendi picture klendi · Oct 19, 2017

As i have heard of, react's require() only uses static url not variables, that means that you have to do require('/path/file'), take a look at this issue on github and this one for more alternative solutions, there are a couple of other ways to do it! for e.g

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

export default images;

then

import Images from './img/index';

render() {
    <Image source={Images.profile.comments} />
}

from this answer