I try to randomly load a gif from an array. I tried several ways to do it but none works. I either get an error message or the image just won’t appear.
Version 1 (result: image doesn’t appear):
var myPix = new Array("../assets/class/emojis/correct/clapping_hands.gif", "../assets/class/emojis/correct/beaming_face_with_smiling_eyes.gif","../assets/class/emojis/correct/confetti_ball.gif","../assets/class/emojis/correct/flexed_biceps.gif");
var randomNum = Math.floor(Math.random() * myPix.length);
var theImage= myPix[randomNum];
return (
<View>
<Image
style={styles.gifAnimation}
source={theImage}
/>
</View>
Version 2 (result: "invalid call")
var myPix = new Array("../assets/class/emojis/correct/clapping_hands.gif", "../assets/class/emojis/correct/beaming_face_with_smiling_eyes.gif","../assets/class/emojis/correct/confetti_ball.gif","../assets/class/emojis/correct/flexed_biceps.gif");
var randomNum = Math.floor(Math.random() * myPix.length);
var theImage= myPix[randomNum];
return (
<View>
<Image
style={styles.gifAnimation}
source={require(myPix[randomNum])}
/>
</View>
Version 3 (result: image won’t load):
const [theImage, setTheImage] = useState();
React.useEffect(() => {
var myPix = new Array(
"../assets/class/emojis/correct/clapping_hands.gif",
"../assets/class/emojis/correct/beaming_face_with_smiling_eyes.gif",
"../assets/class/emojis/correct/confetti_ball.gif",
"../assets/class/emojis/correct/flexed_biceps.gif",
);
var randomNum = Math.floor(Math.random() * myPix.length);
var x = myPix[randomNum];
setTheImage_Correct(x);
source={image_correct
Any thoughts?
2
Answers
I went back to this issue and found out why the images did not load. This is the original code. When using the code, the Gifs simply would not load:
I simply added "require()" for the image sources and it worked well:
Make sure you have implemented the right environment to display GIF as explained below:
By default the Gif images are not supported in android react native app. You need to set use Fresco to display the gif images. The code:
Edit your android/app/build.gradle file and add the following code:
dependencies: {
}
then you need to bundle the app again, You can display the gif images in two ways like this.
As explained in this issue:
How do I display an animated gif in React Native?