Open In App

How to set Background Image in react-native ?

Improve
Improve
Like Article
Like
Save
Share
Report

React Native is a framework developed by Facebook for creating native-style apps for iOS & Android under one common language, JavaScript. Initially, Facebook only developed React Native to support iOS. However, with its recent support of the Android operating system, the library can now render mobile UIs for both platforms.

Prerequisites:

Approach: In this article, we will see that how to set background Image in react-native. In our project, we will simply set a background image and show a text input on top of it.

Below is the step by step implementation:

Step 1: Create a project in react-native using the following command:

npx react-native init DemoProject

Step 2: Create a components folder inside your project. Inside the components, folder create a file BackgroundImage.js.

Project Structure: It will look like the following.

In BackgroundImage.js, we will import ImageBackground component from react-native. It takes following props:

  • source: Source of Image to display. It can be from local storage or url.
  • resizeMode: Resizing of image based on different mobile configurations.

It can be one of the following:

resizeMode: "center" | "contain" | "cover" | "repeat" | "stretch"

BackgroundImage.js




import React from 'react';
import { Text, View, TextInput, ImageBackground, 
    StyleSheet, Dimensions } from 'react-native';
  
const screenHeight = Dimensions.get('window').height;
const screenWidth = Dimensions.get('window').width;
  
const BackgroundImg = () => {
  return (
    <View>
      <ImageBackground
        source={{
          uri: 
        }}
        resizeMode="stretch"
        style={styles.img}>
        <TextInput placeholder="Geeks for Geeks" style={styles.input} />
      </ImageBackground>
    </View>
  );
};
  
export default BackgroundImg;
  
const styles = StyleSheet.create({
  img: {
    height: screenHeight,
    width: screenWidth,
    justifyContent: 'center',
    alignItems: 'center',
  },
  input: {
    height: 40,
    margin: 12,
    borderWidth: 2,
    padding: 10,
  },
});


App.js




import React from 'react';
import type { Node } from 'react';
import { View } from 'react-native';
import BackgroundImg from './components/BackgroundImage';
  
const App: () => Node = () => {
  return (
    <View>
      <BackgroundImg />
    </View>
  );
};
  
export default App;


Step to run the application: Run the application using the following command:

npx react-native run-android

Output:



Last Updated : 07 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads