How to add Background image in React Native

Introduction :

This post will show you how to add one background image in React Native. You don’t have to create one Image component and add it as a background in React Native. React Native provides a component that can be used to set a background image. It is called ImageBackground.

This is similar to the Image component. It also takes the same props. The only difference is that this component is used to add one background image. You can add other components on top of this background image. You need to specify the width and height of this component in style attributes.

In this post, I will show you how to use ImageBackground with an example :

Example program :

The below example shows how to use the ImageBackground component in a react native project. To run this program, you will have to create one react native project and replace the content of App.js with the following code.

import React from "react";
import {
  SafeAreaView,
  StatusBar,
  StyleSheet,
  ImageBackground,
  Button,
} from "react-native";

const App = () => {
  const imageUrl = "../images/robot.png";

  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView style={styles.container}>
        <ImageBackground source={{ uri: imageUrl }} style={styles.image}>
          <Button title="Click me" color="#841584" />
        </ImageBackground>
      </SafeAreaView>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: "column",
    justifyContent: "center",
  },
  image: {
    height: 400,
    width: 400,
  },
});

export default App;

Here,

  • We are using one ImageBackground with a Button. The Button is placed over the image.
  • Since ImageBackground is an inbuilt component in react native, it is imported from react-native.
  • We placed an image robot.png inside the image folder. You can also use a remote image url or any other image.

If you run the above program on an Android device, it will look as like below:

React Native imagebackground

You can also use the ImageBackground component in iOS as well. It is an easy way to add an image background in react native.

You might also like:

React Native Website reference