Bob9630
Bob9630

Reputation: 953

React-Native: Width not inherited from partent view when alignItems is set to 'center'

I am playing around with React-Native again, focusing on layouts this time around, and ran into an interesting problem. If I set alignItems:'center' on a parent View, the children under it don't seem to have their widths properly set.

This code will produce a single green box taking up the whole screen.

React.createClass({
  render: function() {
    return (
      <View style={{flex: 1, alignItems: 'center',backgroundColor:'green'}}>
        <View style={{flex:1, backgroundColor:'blue'}} />      
        <View style={{flex:1, backgroundColor:'red'}} />
      </View>
    );
  }
});

However if I remove the alignItems style or set it to 'stretch' I get a blue box on top of a red box as I would expect

var BrownBag = React.createClass({
  render: function() {
    return (
      <View style={{flex: 1, backgroundColor:'green'}}>
        <View style={{flex:1, backgroundColor:'blue'}} />      
        <View style={{flex:1, backgroundColor:'red'}} />
      </View>
    );
  }
});

What am I missing in my understanding of how alignItems works?

Upvotes: 4

Views: 1261

Answers (1)

Chris Geirman
Chris Geirman

Reputation: 9684

The problem is that when you add alignItems: 'center' the internal items become zero width, so they collapse in on themselves. You can see this yourself by adding some width to the sub-views like so...

    <View style={{flex: 1, backgroundColor:'green', alignItems: 'center'}}>
      <View style={{flex:1, backgroundColor:'blue', width: 300}} />      
      <View style={{flex:1, backgroundColor:'red', width: 300}} />
    </View>

Upvotes: 8

Related Questions