Edit native: how to set Image defaultSource on Android

response native: How to set Image defaultSource on Android.

I have read document React native

1.58. I found defaultSource

iOS-only image prop support .

I need to set the default image on network image upload error.

I wrote the code like this:

{ ImageUrl?
                <Image style={styles.docimg}
                       source={{uri: ImageUrl}}/>
                  :
                <Image style={styles.docimg}
                       source={require('../../../resource/default.png')}/>
              }

      

Now there is a problem. When the url is string type but it is not a valid network image. Since it is a URL true

, the image will show nothing.

I've seen how the Image props onError

can solve my problem.

I need to install a placeholder image.

+3


source to share


2 answers


You just try this and hope it works ...

// initially showDefault will be false
var icon = this.state.showDefault ? require('../../../resource/default.png') : {uri: ImageUrl};

return(
  <Image
    style={styles.docimg}
    source={icon}
    onLoadStart={() => this.setState({showDefault: true})}  
    onLoad={() => this.setState({showDefault: false})}
  />
)

      



Setting showDefault = false in onLoad () should not run fetch url again as images are cached by default in android and IOS.

+3


source


I tried using @ Ravi Raj's answer, but doesn't seem to be related to the image upload error.
Next to the answer, an image will be displayed between the standard and actual image. (Bug reached by @vzhen )

So I developed based on his answer and generated this component. See if it suits you;)

progressive-image.js

- Component <ProgressiveImage/>

import React, { Component } from 'react';
import { Image } from 'react-native';

export default class ProgressiveImage extends Component {
  state = { showDefault: true, error: false };

  render() {
    var image = this.state.showDefault ? require('loading.png') : ( this.state.error ? require('error.png') : { uri: this.props.uri } );

    return (
      <Image style={this.props.style} 
             source={image} 
             onLoadEnd={() => this.setState({showDefault: false})} 
             onError={() => this.setState({error: true})}
             resizeMode={this.props.resizeMode}/>
    );
  }
}

      



Then import and call the component like this:

import ProgressiveImage from './progressive-image';

<ProgressiveImage style={{width: 100, height: 100}} 
                  uri={'http://abc.def/ghi.jpg'} 
                  resizeMode='contain'/>

      

Hope this answer helps you;)

0


source







All Articles