Skip to content

Instantly share code, notes, and snippets.

@AllanGraves
Created December 28, 2020 12:15
Show Gist options
  • Save AllanGraves/a5c1dc925d6262dd08ef3b783b718162 to your computer and use it in GitHub Desktop.
Save AllanGraves/a5c1dc925d6262dd08ef3b783b718162 to your computer and use it in GitHub Desktop.
Dynamically Load and Display an Image in React Native
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