Search code examples
imagereact-nativerequirereact-native-fetch-blob

Require local image downloaded with react-native-fetch-blob


I’m trying to require an image downloaded with react-native-fetch-blob in my Image component, but when I give it the image path it keeps saying me « Unknow named module: ‘/Users/…/Library/…’

What is the right way to require images stored in a local directory ?

let imagePath = null

RNFetchBlob
  .config({
     fileCache : true
  })
  .fetch('GET', uri)
  // the image is now dowloaded to device's storage
  .then((resp) => {
     // the image path you can use it directly with Image component
     imagePath = resp.path()
     this.setState({ uri: require(imagePath) })

     try {
       AsyncStorage.setItem(`${this.props.uri}`, imagePath);
     } catch (error) {
       console.log(error)
     }
  })

My render method :

render() {
    return(
      <Image style={this.props.style} source={this.state.uri} />
    )
}

The problem is not because I set a variable as source because it's working when I put something like : this.setState({ uri: require('../images/test.jpg') }) after my download.


Solution

  • require(imagePath) exists to help packager to find local images and place them to application bundle.

    When you need to show dynamically loaded image, you simple need to pass file location as URI, for ex:

    render() {
      const imageAbsolutePath = this.state.imagePath;
      const imageUri = 'file://' + imageAbsolutePath;
      return <Image source={{uri: imageUri}}/>;
    }
    

    So, you shold not need any require statements in this case.