Create Layout with absolute Values and Flexbox in React Native

143 Views Asked by At

I am a iOS Developer trying to learn React Native. Currently I am trying to figure out how to create a layout like this with FlexBox:

LayoutGoal

I am not sure how to use relative values for with in react native. When I am trying to implement it I am getting this:

Wrong Layout

As you can see, the view in the middle cutting the views on the left and right at there center. Any ideas? Here's my code:

<View style={{flexDirection: 'row', flex: 1}}>
    <SafeAreaView>
      <TouchableOpacity style={{left: 20, top: 24, height: 44, width: 44}}>
        <Image
          source={require('../../assets/images/backButton.png')}
          style={{height: '100%', width: '100%'}}
        />
      </TouchableOpacity>
    </SafeAreaView>
    <View style={{flex: 2, backgroundColor: '#FF2F2F'}}></View>
    <SafeAreaView>
      <Text
        style={{
          right: 20,
          top: 24,
          height: 44,
          fontSize: 14,
        }}>
        1 / 6
      </Text>
    </SafeAreaView>
  </View>
1

There are 1 best solutions below

1
Gavin D'mello On BEST ANSWER

The issue here is that you have incorrectly ordered the classes(View, SafeView, etc) which are causing the layout to overlap and preventing you from getting the desired result.

Check my solution proposed below:

return (
  <SafeAreaView style={{flex: 1}}>
    <View style={{flexDirection: 'row', flex: 1, height: "100%"}}>
      <TouchableOpacity style={{height: 44, width: 44, margin: 10}}>
        <Image
          source={require('../../assets/images/backButton.png')}
          style={{height: '100%', width: '100%'}}
        />
      </TouchableOpacity>
      <View style={{flex: 1, backgroundColor: '#FF2F2F'}}></View>
      <Text
        style={{
          padding: 14,
          fontSize: 14,
        }}>
        1 / 6
      </Text>
    </View>
  </SafeAreaView>
);

Running example for the solution on expo Snack

Feel free to explore and edit it!