Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am completing a tutorial on react native. For a certain screen, the instructor recommends the following code:

<Image source={bgImage} style={styles.backgroundContainer}> 
    <View style={styles.container}>
        <Quote quoteText={this.props.text} quoteSource={this.props.source}/>
    </View>
</Image>

But when I use this, I get the above error.

I've tried alternatives to this, but when I do, the background image doesn't even load.

EDIT: As requested below, here's my styling code. What I'm going for is using a background gradient image stored locally to the app code with text overlayed over that background. What I currently get by using the suggestion below is just the text at the very top of the screen and no background image.

const styles = StyleSheet.create({
  backgroundContainer: {
    flex: 1,
    resizeMode: 'cover',
    width: undefined,
    height: undefined,
    backgroundColor: '#889DAD',
  },
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'transparent',
  },
});
like image 958
Eric LaRue Avatar asked Nov 22 '17 16:11

Eric LaRue


2 Answers

You are not allowed to put other components inside an image component. You need to wrap a View around your Image and positioned it as absolute.

<View style={{ flex: 1}}>
<Image source={bgImage} style={styles.backgroundContainer} /> 
<View style={styles.container}>
    <Quote quoteText={this.props.text} quoteSource={this.props.source}/>
</View>
</View>


container: {
    position: 'absolute',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0, 
    justifyContent: 'center',
    alignItems: 'center',
  },

EDIT: Since react-native version 50.0, you can simply use ImageBackground

like image 107
Tim Avatar answered Oct 20 '22 05:10

Tim


Since react-native 0.50 you can't nest components inside <Image> tag, rather you have to use <ImageBackground> for background images. Release Notes for v0.50.0

like image 18
Shubhnik Singh Avatar answered Oct 20 '22 07:10

Shubhnik Singh