Italo Rodrigo
Italo Rodrigo

Reputation: 1785

Adjust layout React Native

I did a layout below:

<ScrollView style={{flexDirection:'row'}]>
  <View style={{flex:1}}></View>
  <View style={{flex:1}}></View>
  <View style={{flex:1}}></View>
  <View style={{flex:1}}></View>
  <View style={{flex:1}}></View>
  <View style={{flex:1}}></View>
  <View style={{flex:1}}></View>
</ScrollView>

I want 3 columns on each row. But the code print 7 columns.

How to fix?

Upvotes: 0

Views: 80

Answers (1)

nbkhope
nbkhope

Reputation: 7474

The way you have it means the 7 views will occupy the same percentage of space along the row. Adding up the flex numbers yields 7. So each View will occupy 1/7 of the row.

You can go about a solution in two ways:

(1) Divide up the views into groups of 3 views wrapped inside an outer View

(2) Use flexWrap and percentages for the width instead of flex.

Approach 1

<View style={{ flex: 1 }}>
  <View style={{ flex: 1, flexDirection: 'row' }}>
    <View style={{ flex: 1 }}></View>
    <View style={{ flex: 1 }}></View>
    <View style={{ flex: 1 }}></View>
  </View>
  <View style={{ flex:1, flexDirection: 'row' }}>
    <View style={{ flex:1 }}></View>
    <View style={{ flex:1 }}></View>
    <View style={{ flex:1 }}></View> 
  </View>
  <View style={{ flex:1, flexDirection: 'row' }}>
    <View style={{ flex: 1 }}></View>
    <View style={{ flex: 1 }} />
    <View style={{ flex: 1 }}/>
  </View>
</View>

The approach above requires you enclose three views in an outer view, setting flexDirection to row for each outer view so the items inside that container each occupy 1/3 of the space. Note that you have to hardcode two extra views for the last row (unless you use percentage width instead of flex number).

Approach 2

<View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
  <View style={{ width: '33.333%' }}></View>
  <View style={{ width: '33.333%' }}></View>
  <View style={{ width: '33.333%' }}></View>
  <View style={{ width: '33.333%' }}></View>
  <View style={{ width: '33.333%' }}></View>
  <View style={{ width: '33.333%' }}></View>
  <View style={{ width: '33.333%' }}></View>
</View>

In this approach, you don't use the flex number. Instead, you apply percentage widths that correspond to ~33.33% of the screen width. Keep in mind you need the flexWrap style property to be set to wrap. Note you need to set the height for each view otherwise you might see nothing.

Make sure to apply backgroundColor to the different views above during development and debugging otherwise you won't be able to visualize what is going on because they will all have the same background color.

Upvotes: 3

Related Questions