Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load Images in React Native

Semi-new to React Native and i'm having an issue...

I'm trying to require local images based on a variable (an ID stored in a JSON file), I can achieve this if I stored the images online somewhere and used the prop: source:{uri: 'https://www.domian.com'+this.props.model.id'.png'} for example, but obviously require needs just a single string so I can't pass it a variable?

I would just use a lengthy for each/if statement but there will be 100+ options for the image name. Which is another reason i'd rather have the images stored locally.

I've been trying a bunch of different ways but haven't found anything, is there any way around this?

like image 312
AhoySceneBoy Avatar asked Jul 21 '26 17:07

AhoySceneBoy


2 Answers

The following works for me:

// our data
// we need to require all images, 
// so that React Native knows about them statically
const items = [
    {
        id: '001',
        image: require('../images/001.jpeg'),
    },
    {
        id: '002',
        image: require('../images/002.jpeg'),
    },
];

// render
items.map( (item) => 
    <Image key={item.id} source={item.image} />
)

NB: This is based on @soutot's updated answer, but simplified. I don't think there is any need for a boolean.

like image 119
Ben Avatar answered Jul 23 '26 07:07

Ben


AS per your comment and example you mentioned it is like : imageId is JSON and your passing it using props. Is your baseurl same ? then you can achive single string like :

source:{uri: `https://www.domian.com/${this.props.model.id}.png`}

I hope this will work for you : here is example in which I receive part of url to images from different resources, similar to yours:

https://github.com/patilrevansidh/movidb/blob/master/src/modules/movie/detail/screen.js

like image 38
Revansiddh Avatar answered Jul 23 '26 07:07

Revansiddh