React Native - Layout


style guide

flexbox

  1. https://css-tricks.com/snippets/css/a-guide-to-flexbox/
  2. https://facebook.github.io/react-native/docs/layout-props.html#flex
  3. https://medium.freecodecamp.org/understanding-flexbox-everything-you-need-to-know-b4013d4dc9af

all RN components implicitly have display: flex.

flex items (children) are placed inside flex container (parent).

box-sizing

flexbox in RN doesn’t have box-sizing property but flex items behave as if they have box-sizing: content-box (not border-box - that is padding and border are not included in component’s width and height).

flex item properties

flex item and fixed width item in the same row

what we want to get in the end:

|John Doe foo foo foo foo foo...  20 y.o.|
|Jane Doe                         30 y.o.|

here name item is flexible, age item is fixed. but in case of a long name (the 1st row) it wouldn’t be truncated pushing age item to the right => total width of row items becomes larger than the width of flex container:

|John Doe foo foo foo foo foo foo   20 y.o.
|Jane Doe                         30 y.o.|

we need to shrink flexible item (name item) when row items overflow their flex container - use flexShrink: 1 property to achieve this behaviour:

<View style={{flexDirection: 'row'}}>
  <View style={{flex: 1, flexShrink: 1, marginRight: 4}}>
    <Text numberOfLines={1}>{this.props.name}</Text>
  </View>
  <View style={{width: 48}}>
    <Text>{this.props.age}</Text>
  </View>
</View>