4

I have data in such format:

const data = [ { id: '0', title: 'Some title 1' }, { id: '1', title: 'Some title 2' } ... ] 

and I have a folder with images where every image is called '0.png', '1.png', etc, the same amount as the data array length. What I'm trying to do is to map through the data array, displaying the title and the image with the same name as the element's id. For example,

<Image source={require('./images/0.png')} /> 

So I wrote this piece of code:

data.map(item => ( <View> <Image source={require(`./images/${item.id}.png`)} /> <Text>{item.title}</Text> </View> )) 

which gives me this error: Error: TransformError: Invalid call at line 36: require("./images/" + item.id + ".png")

I've also tried it this way:

<Image source={require('./images/' + item.id + '.png')} /> 

When I console.log the path to the image that's created using this concatenation, it looks okay.

By the way, this works just fine:

<Image source={require('./images/' + 10 + '.png')} /> 

and it displays the image named '10.png'

Am I missing something? Please help!

10
  • 2
    Can u try url instead of require? Commented Feb 7, 2020 at 14:31
  • 1
    doesn't work either :/ Commented Feb 7, 2020 at 14:34
  • Use url instead of require. I find it a lot more comfortable. You can also add an onError call so that you handle the case where your image is missing. Commented Feb 7, 2020 at 14:34
  • What error do you get with url? Also, could you console.log the item? Commented Feb 7, 2020 at 14:35
  • Could you please provide an example with url in source? Maybe I’m doing it wrong Commented Feb 7, 2020 at 14:37

1 Answer 1

5

The names used in require need to be known statically. When you add './images/' + 10 + '.png' this immediately translated to ./images/10.png but when you do it dynamically it won't work.

https://facebook.github.io/react-native/docs/images.html

React Native - Image Require Module using Dynamic Names

A solution that gets around this is to add a uri data field to your data and load from there. You can generate it using an external script (for example in python).

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.