react native use variable for image file

2 Solutions Collect From Internet About “react native use variable for image file”

In JS require statements are resolved at bundle time (when the JS bundle is calculated). Therefore it’s not supported to put variable expression as an argument for require.

In case of requiring resources it’s even more trickier. When you have require('./someimage.png'), React Native packager will locale required image and it will be then bundled together with the app so that it can be used as a “static” resource when your app is running (in fact in dev mode it won’t bundle the image with your app but instead the image will be served from the server, but this doesn’t matter in your case).

If you want to use random image as a static resource you’d need to tell your app to bundle that image. You can do it in a few ways:

1) Add it as a static asset of your app, then reference to it with <Image src={{uri:'name_of_the_image_in_assets.png'}}/> (here is how you can add it to the native iOS app)

2) Require all the images upfront statically. Sth in a form of:

var randomImages = [

Then in your code you can do:

<Image src={randomImages[Math.floor(Math.random()*randomImages.length)]}/>

3) Use network image with <Image src={{uri:''}}/>

For anyone getting to know the react-native beast, this should help 🙂

I visited a couple of sites in the past too, but found it increasingly frustrating. Until I read this site here.

It’s a different approach but it eventually does pay off in the end.
Basically, the best approach would be to load all your resources in one place.
Consider the following structure


In index.js, you can do this:

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

export default images;

In your views, you have to import the images component like this:

import Images from './img/index';

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

Everybody has different means to an end, just pick the one that suits you best.