Reputation: 749
I am trying to set a random background image to React Native using expo. Here is the code:
const randomNumber = Math.floor(Math.random() * 53) + 1;
const backimage = `./assets/b${randomNumber}.jpg`;
export default function App() {
return (
<SafeAreaView style={styles.container}>
<ImageBackground source={require(backimage)} style={styles.image}>
<Text>Hello World</Text>
</ImageBackground>
</SafeAreaView>
);
}
I tried the randomNumber and backimage on codepen and it work as expected but not react native.
I also tried hard code the backimage = ./assets/b1.jpg
and it also worked well, but not when I used this: const backimage = ./assets/b${randomNumber}.jpg
;
I am not sure if expo supports string interpolation. Many thanks in advance and greatly appreciated. Thanks again.
Upvotes: 0
Views: 161
Reputation: 1495
In React Native all the files that are being imported are bundled together.The metro bundler needs to know all the files that will be used at compile time
The workaround achieving such scenario e.g
const possiblePaths = {
'one': require('path/to/file/1),
'two': require('path/to/file/2)
}
funtion(type){
return possiblePaths[type]
}
Upvotes: 1