Using Image as a Container in React Native

Bilal Budhani

Bilal Budhani

April 28, 2016

Adding a nice looking background to a screen makes an app visually appealing. It also makes the app look more sleek and elegant. Let us see how we can leverage this technique in React Native and add an image as a background.

We’ll need to create different sizes of the background image, which we’re going to use as a container. React Native will pick up appropriate image based on the device’s dimension (check Images guide for more information).

1- login-background.png (375x667)
2- [email protected] (750x1134)
3- [email protected] (1125x2001)

Now we’ll use these images in our code as container.

1//...
2render() {
3    return (
4      <Image
5        source={require('./images/login-background.png')}
6        style={styles.container}>
7        <Text style={styles.welcome}>
8          Welcome to React Native!
9        </Text>
10        <Text style={styles.instructions}>
11          To get started, edit index.ios.js
12        </Text>
13        <Text style={styles.instructions}>
14          Press Cmd+R to reload,{'\n'}
15          Cmd+D or shake for dev menu
16        </Text>
17      </Image>
18    );
19  }
20//...
21
22const styles = StyleSheet.create({
23  container: {
24    flex: 1,
25    width: undefined,
26    height: undefined,
27    backgroundColor:'transparent',
28    justifyContent: 'center',
29    alignItems: 'center',
30  },
31});

We’ve intentionally left height and width of the image as undefined. This will let React Native take the size of the image from the image itself. This way, we can use Image component as View and add other components as a children to build UI.

image as container in react native

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.