Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a local image after loading a remote image failed

Tags:

react-native

Is it possible to load a local image if the remote image failed?

For example, I have the following code:

<Image style={ styles.userImage }
       source={ { uri: http://example.com/my_image.jpg } }
       onError={(error) => ...}
/>

In case for example I don't have the rights to access http://example.com/my_image.jpg, I'll get an error in onError. Is there a way then to load a local image instead?

like image 528
Nico Avatar asked May 17 '16 04:05

Nico


People also ask

How do I set a default image in React?

You can simply do this. First, you can use useState like this and give your intended image. in the setImgSrc() give the image you want as the default. Hope this was helpful!


2 Answers

Use component' state. In your constructor set initial url:

 this.state = { image: { uri: 'http://example.com/my_image.jpg' } }

Create onError handler:

 onError(error){
   this.setState({ image: require('your_local_image.path')})
 }

And then combine it all together:

 <Image style={ styles.userImage }
       source={ this.state.image }
       onError={ this.onError.bind(this) }
 />
like image 55
Ivan Chernykh Avatar answered Sep 21 '22 06:09

Ivan Chernykh


As per the latest docs you can use defaultSource property. It shows the image till the original image loads, if the load fails the default image is shown Link to docs

like image 31
Vinoth Kumar Avatar answered Sep 19 '22 06:09

Vinoth Kumar