본문 바로가기
Java, JavaScript/React-Native

react native use variable for image file

by swconsulting swconsulting 2018. 9. 23.

SOURCE:


https://stackoverflow.com/questions/33907218/react-native-use-variable-for-image-file





In JS require statements are resolved at bundle time (when the JS bundle is calculated). Therefore it's not supported to put variable expression as an argument for require.

In case of requiring resources it's even more trickier. When you have require('./someimage.png'), React Native packager will locale required image and it will be then bundled together with the app so that it can be used as a "static" resource when your app is running (in fact in dev mode it won't bundle the image with your app but instead the image will be served from the server, but this doesn't matter in your case).

If you want to use random image as a static resource you'd need to tell your app to bundle that image. You can do it in a few ways:

1) Add it as a static asset of your app, then reference to it with <Image src={{uri:'name_of_the_image_in_assets.png'}}/> (here is how you can add it to the native iOS app)

2) Require all the images upfront statically. Sth in a form of:

var randomImages = [
    require('./image1.png'),
    require('./image2.png'),
    require('./image3.png'),
    ...
];

Then in your code you can do:

<Image src={randomImages[Math.floor(Math.random()*randomImages.length)]}/>

3) Use network image with <Image src={{uri:'http://i.imgur.com/random.jpg'}}/>





class ImageContainer extends Component {
   this.state ={
     image:require('default-img')
   }
    <View>
           <Image source={this.state.image} />
    </View>
}

In the context of this discussion,I had this case where wanted to dynamically assign images for a particular background. Here I change state like this

this.setState({
  image:require('new-image')
})





'Java, JavaScript > React-Native' 카테고리의 다른 글

iPhone Display Size  (0) 2018.09.29
DPI Meaning  (0) 2018.09.25
react native use variable for image file  (0) 2018.09.23
image and touchableOpacity  (0) 2018.09.23
Background Images in React Native  (0) 2018.09.23
How to overlap view in react native  (0) 2018.09.22

댓글0