How to display image from variable in react native
Use FlatList to render array of items and it has lazy loading so it will be good when you use large amount of data.
In your case use this code and it will be working fine:
var [data, setData] = useState([
{
id: 1,
src: require("../assets/image.jpg"),
},
{
id: 2,
src: require("../assets/image2.jpg"),
},
])
return (
<SafeAreaView>
<FlatList
data={data}
showsVerticalScrollIndicator={false}
renderItem={({item}) => (
<Image
source={item.src}
style={styles.imageStyle}
/>
)}
keyExtractor={item => item.id.toString()}
/>
</SafeAreaView>
How to save an image to a variable using url react native
No need to "save" the url in a variable.
Simply assign the url to a variable, for example:
const imageUri = 'https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.laramind.com%2Fblog%2Fpercorso-react-native-dal-livello-base-al-livello-avanzato%2F&psig=AOvVaw2Kb7DOrxfQ9hHdyuf-9m49&ust=1626099973147000&source=images&cd=vfe&ved=0CAoQjRxqFwoTCLDDv8yc2_ECFQAAAAAdAAAAABAD'
And use it in your image component:
<Image src={{uri: imageUri}}/>
To use it offline you need to use an external library such as rn-fetch-blob, here an example app on how to do it:
// How to Download an Image in React Native from any URL
// https://aboutreact.com/download-image-in-react-native/
// Import React
import React from 'react';
// Import Required Components
import {
StyleSheet,
Text,
View,
TouchableOpacity,
PermissionsAndroid,
Image,
Platform,
} from 'react-native';
// Import RNFetchBlob for the file download
import RNFetchBlob from 'rn-fetch-blob';
const App = () => {
const REMOTE_IMAGE_PATH =
'https://raw.githubusercontent.com/AboutReact/sampleresource/master/gift.png'
const checkPermission = async () => {
// Function to check the platform
// If iOS then start downloading
// If Android then ask for permission
if (Platform.OS === 'ios') {
downloadImage();
} else {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: 'Storage Permission Required',
message:
'App needs access to your storage to download Photos',
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
// Once user grant the permission start downloading
console.log('Storage Permission Granted.');
downloadImage();
} else {
// If permission denied then show alert
alert('Storage Permission Not Granted');
}
} catch (err) {
// To handle permission related exception
console.warn(err);
}
}
};
const downloadImage = () => {
// Main function to download the image
// To add the time suffix in filename
let date = new Date();
// Image URL which we want to download
let image_URL = REMOTE_IMAGE_PATH;
// Getting the extention of the file
let ext = getExtention(image_URL);
ext = '.' + ext[0];
// Get config and fs from RNFetchBlob
// config: To pass the downloading related options
// fs: Directory path where we want our image to download
const { config, fs } = RNFetchBlob;
let PictureDir = fs.dirs.PictureDir;
let options = {
fileCache: true,
addAndroidDownloads: {
// Related to the Android only
useDownloadManager: true,
notification: true,
path:
PictureDir +
'/image_' +
Math.floor(date.getTime() + date.getSeconds() / 2) +
ext,
description: 'Image',
},
};
config(options)
.fetch('GET', image_URL)
.then(res => {
// Showing alert after successful downloading
console.log('res -> ', JSON.stringify(res));
// res.base64()
// res.path()
alert('Image Downloaded Successfully.');
});
};
const getExtention = filename => {
// To get the file extension
return /[.]/.exec(filename) ?
/[^.]+$/.exec(filename) : undefined;
};
return (
<View style={styles.container}>
<View style={{ alignItems: 'center' }}>
<Text style={{ fontSize: 30, textAlign: 'center' }}>
React Native Image Download Example
</Text>
<Text
style={{
fontSize: 25,
marginTop: 20,
marginBottom: 30,
textAlign: 'center',
}}>
www.aboutreact.com
</Text>
</View>
<Image
source={{
uri: REMOTE_IMAGE_PATH,
}}
style={{
width: '100%',
height: 100,
resizeMode: 'contain',
margin: 5
}}
/>
<TouchableOpacity
style={styles.button}
onPress={checkPermission}>
<Text style={styles.text}>
Download Image
</Text>
</TouchableOpacity>
</View>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
button: {
width: '80%',
padding: 10,
backgroundColor: 'orange',
margin: 10,
},
text: {
color: '#fff',
fontSize: 20,
textAlign: 'center',
padding: 5,
},
});
Reactjs: How to import an image from a variable path
You can try with:
Using import
for browser and nodejs
const picture = (await import(`../path/to/file/${this.props.picPath}`)); // this is async
Using require
for browser and nodejs
const picture = require(`../path/to/file/${this.props.picPath}`); // this is sync
Using readFileSync
from fs
only for nodejs
const fs = require('fs')
// or: import fs from 'fs'
const file = fs.readFileSync(`../path/to/file/${this.props.picPath}`).toString()
Using readFile
from fs
only for nodejs
const fs = require('fs')
// or: import fs from 'fs'
const file = (await fs.readFile(`../path/to/file/${this.props.picPath}`)).toString()
Tip #1:
When you using require, it only can handle json and js files, but when you using import, it can handle svg, and other stuff.
But you can apply some trick like:
// in tsconfig.json
"include": [
"./declarations.d.ts",
],
// in declaration.d.ts
declare module '*.png';
Tip #2:
When you wanna import images like png
, you should be define how it work with this:
declare module "*.png" {
const value: any;
export default value;
}
Tip #3
In javascript you can use Template Literals using ``
and ${}
.
const name = "John"
console.log(`Hello ${name}`);
Setting source of Image/ with variable
You try like this
const items = [{ name: require('./images/home.png'), code: '#1abc9c' },{...}]
then
<Image source={item.name}></Image>
Related Topics
How to Change Fontsize by JavaScript
How to Get Just Numeric Part of CSS Property with Jquery
How Does This Object Method Definition Work Without the "Function" Keyword
Queryselector and Queryselectorall VS Getelementsbyclassname and Getelementbyid in JavaScript
Change the Url in the Browser Without Loading the New Page Using JavaScript
CSS Hover VS. JavaScript Mouseover
How to Read and Write into File Using JavaScript
How to Use the Spacing Utility Classes in Bootstrap
How to Find Object in Array by Property in JavaScript
Jquery Drag/Resize with CSS Transform Scale
What's the Right Way to Decode a String That Has Special HTML Entities in It
Leaflet Map Not Displayed Properly Inside Tabbed Panel
How to Provide Named Parameters in a Function Call in JavaScript
How to Set a Cookie for Another Domain