Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "TransformError: Invalid call" when trying to use require with string concatenation

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!

like image 922
Christine H. Avatar asked Sep 03 '25 06:09

Christine H.


1 Answers

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).

like image 129
Mike Avatar answered Sep 04 '25 19:09

Mike