1

Problem with dynamic loading of image resources within a loop/list.

I have all my static local resources required as such:

assets/images.js

const images = { appLogo: require('./app-logo.png'), cardOne: require('./cards/card-1.png'), cardTwo: require('./cards/card-2.png'), ... cardForty: require(./cards/card-40.png) } export default images; 

Then in my list screen:

... import images from '../assets/images'; ... renderListItems(item) { const image_name = `images.card${item.cardName}`; console.log(image_name); // images.cardOne, images.cardTwo etc.. return ( <ListItem avatar> <Thumbnail square size={80} source={image_name} /> // This is nativebase component which wraps the RN image component <Body> <Text>{item.name}</Text> </Body> <Right> <NBIcon name="arrow-forward" /> </Right> </ListItem> ); } ... 

No resources get loaded. Yet if I change the source={image_name} to source={images.cardOne} directly (where images.cardOne is the exact same as image_name variable on the first iteration) it works - except for the fact that they all have the same image.

I also tried using {{ uri: image_name }} syntax but nothing happens there too.

There doesn't seem to be any solution to this, other than creating a massive switch statement

1 Answer 1

1

Well that's because image_name is a string with the value of images.cardOne whereas images.cardOne is also a string but with the value of the actual path of the images in your file system (e.g ./app-logo.png). So if you want to load images object dynamically to image_name, you should use the bracket notation like so:

const image_name = images[`card${item.cardName}`];

That way image_name will now point to the path of your images (e.g ./app-logo.png).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.