0

I want to load a default image if the image URL gives a 404 error. I tried onError() in image prop but it's not working.

<Image
              onError={() => {
                setError(true);
              }}
              source={{
                uri: error
                  ? imageUrl
                  : "https://logodownload.org/wp-content/uploads/2019/07/udemy-logo-5.png",
              }}
              style={{
                height: 50,
                width: "100%",
                alignItems: "center",
                justifyContent: "center",
              }}
              resizeMode="cover"
            />


How can I do this thing?

Harsh Mishra
  • 862
  • 3
  • 15
  • 29

2 Answers2

1

You can use defaultSource in your Image with default image which results in displaying default image when the provided imageUrl fails to load

var defaultImage = yourDefaultImageURl 

And in your Image

    <Image
    defaultSource={defaultImage}
    source={{uri: imageUrl}}
       style={{
            height: 50,
            width: "100%",
            alignItems: "center",
            justifyContent: "center",
          }}
   resizeMode="cover"
   />
Ruchi Tiwari
  • 261
  • 1
  • 4
1

In that case how about just placing the default url in error

 onError={() => {       
 setImageUrl('https://logodownload.org/wpcontent/uploads/2019/07/udemy-logo-5.png');
          }}

And in source

       source={{uri:imageUrl}}
Ruchi Tiwari
  • 261
  • 1
  • 4
  • This will set the image URL for all if one image fails to load. – Harsh Mishra Jul 22 '21 at 17:10
  • As per the question placed i understand it to be used for a single Image and then this works fine. Are you loading the same imageUrl elsewhere? – Ruchi Tiwari Jul 22 '21 at 17:26
  • Yes for the single image it's fine. But I am getting images from the server. – Harsh Mishra Jul 22 '21 at 17:32
  • In that case you can maintain respective ids and flag for each imageUrls and maintain the state accordingly. Doing so can help in refreshing and loading the images with the imageUrls fetched and also the error state. – Ruchi Tiwari Jul 22 '21 at 17:42