I am developing UI in react native, In this <Image>
is used with source and i wanted to change the image source by setNativeProps not by state.
my code is:
<Image source={require('imagePath')} ref="icon"/>
On certain Event i want to change its source:
this.refs['icon'].setNativeProps({
source: require('newImagePath')
});
But nothing happens, its not change.
By using NativeProps the style of image is changed but the props like source and like that not changes.
So please give me a solution that how can i change the source of image on any certain event by using its refs or key (not by using this.setState)
Finally I found the way you can change the image source by static image. We first need to use resolveAssetSource function to the static image and then put it in src.
import resolveAssetSource from 'resolveAssetSource';
...
var imgsrc = require('imagePath');
this.refs['icon'].setNativeProps({
src: [resolveAssetSource(imgsrc)]
});
Update:
On IOS, use source instead of src.
Thanks to @DennisFrea who gave the answer I was looking for - simply adding the source as an array instead of an object.
Correct syntax
this._imageContainer.setNativeProps({
source: [{ uri: newImageSource }]
})
Incorrect syntax
this._imageContainer.setNativeProps({
source: { uri: newImageSource }
})
I am towards thinking this is not possible because of the way RN handles the states and the way require() bundles the files.
However, I can think of two things to try:
- ForceUpdate: Try calling this.refs['icon'].forceUpdate() after the native props to force a re render.
- Set a wrapper in your image and update that wrapper, so you don't modify the original image source.
Something like this: Programmatically add a component in React Native