Created
December 28, 2020 12:15
-
-
Save AllanGraves/a5c1dc925d6262dd08ef3b783b718162 to your computer and use it in GitHub Desktop.
Dynamically Load and Display an Image in React Native
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as FileSystem from 'expo-file-system'; | |
const foo = require('./assets/images/photo1.jpg'); | |
const fooURI = Image.resolveAssetSource(foo).uri; | |
console.log('FooURI: ' + fooURI); | |
const App: () => React$Node = () => { | |
const [imageDownloaded, setImageDownloaded] = useState(0); | |
const docDir = FileSystem.documentDirectory; | |
const localFile = 'file://' + docDir + 'photo1.jpg'; | |
if (imageDownloaded) { | |
dlImage = <Image style={{height:50, width:50}} source={{uri: localFile}} />; | |
} | |
else | |
{ | |
dlImage = <Text> No Image </Text>; | |
} | |
return ( | |
<> | |
<StatusBar barStyle="dark-content" /> | |
<SafeAreaView> | |
<Button | |
onPress={() => { | |
console.log('Using :' + docDir); | |
FileSystem.downloadAsync(fooURI, localFile) | |
.then(({uri}) => { | |
console.log('Finished downloading to ' + uri); | |
setImageDownloaded(1); | |
FileSystem.readDirectoryAsync('file://' + docDir) | |
.then((dir) => { | |
dir.forEach((val) => { | |
console.log('File: ' + val); | |
}); | |
}) | |
.catch(() => { | |
console.log('Error reading directory: ' + docDir); | |
}); | |
}) | |
.catch((error) => { | |
console.error(error); | |
}); | |
}} | |
title="click me" | |
/> | |
<Text> DL: {imageDownloaded} </Text> | |
{dlImage} | |
</SafeAreaView> | |
</> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment