Using Image as a Container in React Native

Bilal Budhani

By Bilal Budhani

on 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- login-background@2x.png (750x1134)
3- login-background@3x.png (1125x2001)

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

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  }
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  },

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

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.