user3259472
user3259472

Reputation:

React Native: Why don't flex justifyContent and alignItems work for child <View/>?

In React Native, I have a child view inside another view, but it doesn't center in the middle of the page. But if the child view is not inside the parent view and alone, it centers fine in the middle of page.

How can I make it so that the child view centers to the middle of the page while being inside another view (parentView)?

Here is the code:

  render() {

    return (
      <View id="parentView">
          <View
            id="childView" 
            style={
               flex: 1,
               justifyContent: 'center',
               alignItems: 'center',
            }
          >
            <Text>Center This to Middle of Page</Text>
          </View>
          <View
            id="childViewTwo" 
          >
            <Text>Don't center me</Text>
          </View>
      </View>
    );
  }

Upvotes: 3

Views: 7054

Answers (1)

Mila
Mila

Reputation: 608

Just add flex:1 to your parent View. I made a working example for you: https://rnplay.org/apps/zHO1YA

return (
       <View id="parentView" style={{flex: 1}}>
          <View
            id="childView" 
            style={{
               flex: 1,
               justifyContent: 'center',
               alignItems: 'center',
            }}
          >
            <Text>Center This to Middle of Page</Text>
          </View>
          <View
            id="childViewTwo" 
          >
            <Text>Don't center me</Text>
          </View>
      </View>
    );

Upvotes: 6

Related Questions