0

I need to add 3 buttons per row. Since there are many device sizes I fear that my code will return different number of buttons per row. How can I sort this ?

So what ever the device width it is, the code should always return only 3 buttons per row. The width of the button should auto-shrink based on the width to accommodate 3 buttons per row.

My code, at the moment returns 3-buttons per row, but the number changes when the width of the screen changes.

...
  mygetButtons = () => {
    const buttons = [];
    for( let i = 0; i < 9; i++) {
       buttons.push(
         <TouchableOpacity style={styles.but}  key={i}>

            <Text> Hi </Text>

         </TouchableOpacity>
      )
    }
    return buttons;
  }

...

<View style={styles.frame}>
      {this.mygetButtons ()}
</View>

...

  frame: {
    flex: 0.5,
    flexDirection: 'row',
    flexWrap: 'wrap',
    width: window.width
  },
  but: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    paddingTop: 15,
    paddingRight : 115,
    paddingLeft: 5,

  }
halfer
  • 19,824
  • 17
  • 99
  • 186
Illep
  • 16,375
  • 46
  • 171
  • 302
  • Well, I'm not familiar with react but in 'normal' Android you'd do this using [LinearLayout](https://developer.android.com/guide/topics/ui/layout/linear.html) and [layout_weight](https://stackoverflow.com/questions/3995825/what-does-androidlayout-weight-mean) – Ch4t4r Aug 15 '17 at 06:04
  • You can use View by giving it flexWrap... See [this](https://stackoverflow.com/questions/45328984/draw-a-view-with-image-pattern/45329732#45329732) answer it will help – tahir mahmood Aug 15 '17 at 12:07

2 Answers2

2

You can archive this by using Dimensions as @Qop mentioned here

another way is to use one package react-native-easy-grid that allows you to create row and column based on requirement without worrying about device sizes,

import:

import { Col, Row, Grid } from "react-native-easy-grid";

use:

<Grid>
    <Col></Col>
    <Col></Col>
</Grid>

This will create two column with equal width i.e. 50% of device width

Jigar Shah
  • 6,143
  • 2
  • 28
  • 41
0

You can use Dimensions.width in order to achieve that.

Set your frame and button width as you wish

const {width} = Dimensions.get('window');

const frameWidth = width;
const columnWidth = frameWidth / 3;

and use them

frame: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    alignItems:'flex-start',
    justifyContent:'flex-start',
    width: frameWidth,
    backgroundColor:'blue',
},
but: {
    width: columnWidth,
    paddingTop: 15,
    paddingBottom: 15,
    alignItems:'center',
    backgroundColor:'green'
}

working example

QoP
  • 27,388
  • 16
  • 74
  • 74