Ishaq Ashraf
Ishaq Ashraf

Reputation: 169

react native background image

I need help. I want to add content on the below background image This is my code :

<View style={{flex:1}}>
                <Image
                style={styles.mainContainer}
                source={require('../images/samples/login_bg.png')}>
                <LoginForm/>
                </Image>
            </View>

It shows me this error :

Error: The  component cannot contain children. If you want to render content on top of the image, consider using absolute positioning.

Upvotes: 0

Views: 724

Answers (2)

Manoj Prabhakar
Manoj Prabhakar

Reputation: 1016

From React Native Official Documentation:

A common feature request from developers familiar with the web is background-image. To handle this use case, you can use the component, which has the same props as , and add whatever children to it you would like to layer on top of it.

You might not want to use in some cases, since the implementation is very simple. Refer to 's source code for more insight, and create your own custom component when needed.

return (
  <ImageBackground source={...}>
    <Text>Inside</Text>
  </ImageBackground>
);

You can try

<View style={{flex:1}}>
    <ImageBackground
    style={styles.mainContainer}
    source={require('../images/samples/login_bg.png')}>
       <LoginForm/>
    </ImageBackground>
</View>

Upvotes: 2

Ryan Turnbull
Ryan Turnbull

Reputation: 3934

You can, as you mentioned, position your image absolutely in order to have all other items flexed within your container. By doing it like this, all of your other components will still follow all of your flex positioning styles, and the image would simply be in the background. Note: you must have the image defined first, as

components are rendered in the order of definition.

This is the way id do it also, like so

<View style={{flex:1}}>
    <Image
       style={styles.mainContainer}
       source={require('../images/samples/login_bg.png')}>
    </Image>
    <LoginForm/>
</View>

and in styles (Note: this will place the image at the top left of the parent view)

mainContainer: {
    position: 'absolute'
    left: 0,
    top: 0
}

and then you can play around with the image dimensions, for example setting width to Dimensions.get("window").width would fill the screen horizontally. I believe you'd have to handle the stretch of the image, so have a look here

Upvotes: 0

Related Questions