How to Include Dynamic Image in React Native
Sometimes we need to include images dynamically in our React Native app. These images change conditionally or when a user clicks a button or takes action.
We can use the function require()
to dynamically require the image module by passing the image’s path.
In this article, we will learn how we can dynamically include images in a React Native app. Also, we will make the topic easier by providing necessary examples and explanations.
For this purpose, we will use a function named required()
. Let’s see an example to make the topic easier.
Add Dynamic Image in the React Native App
In our below example, we illustrated how we could include an image dynamically in a React Native app. Let’s take a look at the following code:
// Importing necessary packages
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Image, Text, View } from 'react-native';
// Our main function
export default function App() {
let img = "./assets/image2.jpg"; // Declaring a variable that hold the image location
return (
<View style={styles.container}>
<Text>Simple Image</Text>
<Image style={styles.img} source={require(img)} />
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({ // Providing some styles to the UI
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
marginTop: 100,
},
img: {
width: '100%',
height: 120,
},
});
We’ve already commanded the purpose of each line. In the above example code, we first created a variable named img
which will hold the image location.
After that, we just passed that variable to the require()
function that will load the image from the specific location. Now, after executing the above example, you may get the output like the below:
Output:
Please note that the example code shared above is created in React Native, and we used the Expo-CLI
to run the app.
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
LinkedInRelated Article - React Native
- How to Align Text Vertically in React-Native
- How to Set Font Weight in React Native
- How to Align Text in React-Native
- How to Animate SVG in React Native
- How to Set the Border Color in React-Native
- React Native Foreach Loop