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',
  },
});

Answers:

Answer

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

Answer

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

Answer

Use

<ImageBackground
    source={image}
    style={styles.contentContainer} >
    // Your view content goes here

 </ImageBackground>

const styles = StyleSheet.create({
    contentContainer: {
        flex: 1,
  },
});

Works like a charm

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.