Background images on React Native

Reading Time: 2 minutes

Background images are a common use case on mobile applications. React Native version 46.4 makes this easier to accomplish. In this post, I will create a simple demo of how to use the ImageBackground component, introduced in React Native 46.

Note: Before getting started to make sure you have React Native installed in your machine.

  • Create a new React Native project by running react-native init backgroundImage.
  • Change your current path to the project directory cd backgroundImage.
  • Start the app to make sure the installation completed successfully by running react-native run-ios.
    You should see this React Native starter view:
  • Create an images folder in your project root directory. Save and drag this image to that folder.
  • Edit the boilerplate code to make sure you import as the following:
import {
  Platform,
  StyleSheet,
  Text,
  View,
  ImageBackground,
  Image
} from 'react-native';
  • Adjust your render method to look like the following:
render() {
    return (
      <ImageBackground
        style={styles.container}
        source={require('./images/background.png')}
        imageStyle={{ resizeMode: 'cover' }}
      />
    );
  }
  • You should see this empty background image:
  • Update your code to the following to insert nested components in the image:
<ImageBackground
        style={styles.container}
        source={require('./images/background.png')}
        imageStyle={{ resizeMode: 'cover' }}
      >
        <Text>My Background Image</Text>
      </ImageBackground></pre>
            
  • You should see the text on top of the image:
  • Finally, apply some styling to the text component:
    <Text
          style={{
            backgroundColor: 'rgba(0,0,0,0)',
            color: 'white'
          }}
        >
          My Background Image
        </Text>
  • Your end result should look like this:

The ImageBackground component is officially supported by Facebook and should be the preferred method to implement this feature.

One last note, in case you do not want your background image to fill all the screen space, you can add a parent View component and give your image the desired width and height. I will leave this exercise to you and you can comment on how it went.

If you want to know more about this topic, please contact us!

0 Shares:
You May Also Like