Gaurav Arora
Gaurav Arora

Reputation: 17264

React Native: issue with flex layout

I'm trying to make a simple view with 2 subviews - v1, v2 aligned horizontally and each taking 50% of the screen width.

enter image description here

To achieve this, I'm using the following code:

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

I've also tried playing with other attributes- flexWrap, justifyContent.

However, everytime the views get stacked one after the other and doesn't take 50% of the screen. What am I doing wrong?

EDIT: The actual piece of code I'm using:

  <View>
    <Text style={styles.place}>New Delhi</Text>
    <View style={{flexDirection: 'row'}}>
      <DayTimeComponent style={{flex:1}}/>
      <DayTimeComponent style={{flex:1}}/>
    </View>
    </View>

Upvotes: 0

Views: 391

Answers (2)

BK7
BK7

Reputation: 1181

You can achieve this easily using react-native-easy-grid

Code:

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

export default class StackOverflow extends Component {

  render() {
    return (
      <View style={{flex:1}}>
       <Grid>
        <Col style={{backgroundColor:'yellow',alignItems:'center',justifyContent:'center'}}><Text>v1</Text></Col>
        <Col style={{backgroundColor:'green',alignItems:'center',justifyContent:'center'}}><Text>v2</Text></Col>
       </Grid>
      </View>
    );
  }
}

Result:

enter image description here

You can also create custom layouts, for eg: if you need a 75%-25% split then all you need to do is

<Col size={75}></Col>
<Col size={25}></Col>

Upvotes: 3

Daniel Basedow
Daniel Basedow

Reputation: 13396

Set "flex:1" on both the container views. Like so:

<View style={{flex:1}}>
    <Text style={styles.place}>New Delhi</Text>
    <View style={{flexDirection: 'row', flex:1}}>
        <DayTimeComponent style={{flex:1}}/>
        <DayTimeComponent style={{flex:1}}/>
    </View>
</View>

Upvotes: 0

Related Questions