Nat
Nat

Reputation: 749

React Native Random BackImage with Expo

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

Answers (1)

Muhammad Iqbal
Muhammad Iqbal

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

Related Questions