Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two column layout in react native

I want to display multiple elements in two columns in a react native application. This is what I have so far:

class App extends Component {
  render() {
    const { viewStyle, childStyle } = style;

    return (
      <View style={viewStyle}>
        <View style={childStyle} />
        <View style={childStyle} />
        <View style={childStyle} />
        <View style={childStyle} />
        <View style={childStyle} />
        <View style={childStyle} />
        <View style={childStyle} />
        <View style={childStyle} />
        <View style={childStyle} />
      </View>
    );
  }
}

const space = 5;
const style = {
  viewStyle: {
    flex: 1,
    flexWrap: 'wrap',
    flexDirection: 'row',
    padding: space,
    marginTop: 20,
    backgroundColor: 'green'
  },
  childStyle: {
    width: '50%',
    height: 100,
    backgroundColor: 'red',
    borderWidth: 1,
    borderColor: 'black',
    marginBottom: space
  }
}

And here is a screenshot: https://imgur.com/a/wKgDR

My problem is: How can I get some space in the middle (between the left and the right elements)? And is it possible, that this also works when the user rotates the device?

like image 696
23tux Avatar asked Nov 18 '22 23:11

23tux


1 Answers

You could have a container with flexDirection: 'row', such that your columns are inside of this. Then have an empty View inserted between your columns:

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

<View style={{flex: 1, flexDirection: 'row', width: width}}>
    <View style={[viewStyle, {flex: 5, flexDirection: 'column'}]>
        <View style={childStyle} />
        <View style={childStyle} />
        ...
    </View>

    <View style={{flex: 1}}>
    </View>

    <View style={[viewStyle, {flex: 5, flexDirection: 'column'}]>
        <View style={childStyle} />
        <View style={childStyle} />
        ...
    </View>
</View>

Difficult to maintain a fixed pixel dimension like this, but it will size on screen rotation. Alternatively you could just use padding in your column Views to have space between them. You could also disable screen orientation changes if you wanted to go that far. Hope this helps!

like image 83
kwishnu Avatar answered Jun 16 '23 17:06

kwishnu