Quantcast
Channel: Active questions tagged react-native+android - Stack Overflow
Viewing all articles
Browse latest Browse all 28476

Image using uri as source not shown

$
0
0

I have a react native App which downloads images from external sources and saves them into dedicated local cache folder. Later they get displayed in different views. The images are initially not available in the app bundle.

<Image source={{uri: uri}} resizeMode="contain" style={style} />

I use the URI format for the source input parameter of Image component referring a local folder. I pass width and height as style as well, in fact the image size is always known before drawing. It works fine on iOS but not on Android.

As the documentation says, I should use require('') for local images on Android. This works for static images but not for downloaded on run time.

Has anybody idea how could I solve this issue?

Here is the code:

class CachedImage extends React.Component {
    state = {
        uri: null
    }

    async _handleCache(source) {        
        const path = `${RNFetchBlob.fs.dirs.CacheDir}${sha1(source.uri).toString()}.jpg`;        
        const exists = await RNFetchBlob.fs.exists(path);
        if (exists) {
            this.setState({uri: path});                
        } else {
            // encoding the file to preserve proper URL transmition
            await RNFetchBlob
                .config({path})
                .fetch("GET", source.uri, {});
            this.setState({uri: path});
        }
    }

    componentWillMount() {
        this._handleCache(this.props.source).done();
    }

    render() {
        const { style } = this.props;

        if (this.state.uri != null) {            
            return (                
                <Image source={{uri: this.state.uri}} resizeMode="contain" style={style} />
            );
        }
        return(
            <View style={style}/> //todo: display activity while loading ...
        );
    }
}

Usage:

<CachedImage
   style={{width: _width , height: _height}}
   source={{uri: 'http://...'}} />

Viewing all articles
Browse latest Browse all 28476

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>