Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

react-native

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?

like image 920
Bob9630 Avatar asked Mar 14 '23 03:03

Bob9630


1 Answers

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>
like image 97
Chris Geirman Avatar answered Apr 03 '23 02:04

Chris Geirman