Search code examples
react-nativetextviewcomponentsoverlay

Why is my text not being displayed in my imported view?


I imported a simple view named BackgroundContainer, which I wanted to use as a background component for a lot of screens. But everything I put in to it won't be displayed and it seems like the content ist overlaid by the view. Why ist this the case? It's working if I set the style manually for the view and do not import it as shown in the comments below.

Here is the screen the component gets imported to:

import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';

import BackgroundContainer from '../components/BackgroundContainer';

export default function Leaderboard(props) {

    return (
        <BackgroundContainer>   
        {/*if you replace this with "<View style={styles.container2}></View>" it's working*/}
            <View style={styles.container}>
                <Text>Leaderboard</Text>   
                {/*not displayed*/} 
            </View>
        </BackgroundContainer>

    );

}

const styles = StyleSheet.create({
    container: {
        paddingTop: 60,
        alignItems: 'center',
    },
    container2: {
        flex: 1,
        backgroundColor: '#EFFBEF', alignItems: 'center', justifyContent: 'center'
    },
    text: {
        fontSize: 42,
        color: "black",
        padding: 5,
        margin: 10,
        backgroundColor: "red",
    }
});

And here ist the component:

import React from 'react';
import {StyleSheet, View, Text} from 'react-native';

export default function BackgroundContainer(props) {
    return (
        <View style={styles.container}></View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#EFFBEF',
        alignItems: 'center',
        justifyContent: 'center'
    }
});


Screenshot of the result:

text not displaying on screen


Solution

  • You need to render props.children in you BackgroundContainer.

    export default function BackgroundContainer(props) {
        return (
            <View style={styles.container}>{props.children}</View>
        );
    }
    

    See A quick intro to React’s props.children