Search code examples
cssreact-nativeflexboxreact-native-flexbox

Having difficulty in using flexbox in react native


I have this design that I am trying to make in react native but could not properly arrange using flexbox.

Desired Result

The design.

My Code

import React from 'react';
import { View, Text, StyleSheet } from 'react-native'
import Touchable from 'react-native-platform-touchable';

class Dashboard extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return(
      <View style={styles.container}>
        <View style={styles.row}>
          <Touchable style={styles.widgets}>
            <View><Text> Hello Dashboard </Text></View>
          </Touchable>

          <Touchable style={styles.widgets}>
            <View><Text> Hello Dashboard </Text></View>
          </Touchable>
        </View>

        <View style={styles.row}>
          <Touchable style={styles.widgets}>
            <View><Text> Hello Dashboard </Text></View>
          </Touchable>

          <Touchable style={styles.widgets}>
            <View><Text> Hello Dashboard </Text></View>
          </Touchable>
        </View>

        <View style={styles.row}>
          <Touchable style={styles.widgets}>
            <View><Text> Hello Dashboard </Text></View>
          </Touchable>

          <Touchable style={styles.widgets}>
            <View><Text> Hello Dashboard </Text></View>
          </Touchable>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'flex-start'
  },
  row: {
    flex: 1,
    flexDirection: 'row',
    height:120,
    marginTop: 15,
    marginBottom: 15,
  },
  widgets: {
    backgroundColor: '#fff',
    elevation: 2,
    width: '44%',
    marginLeft: 15,
    marginRight: 15
  }
})

export default Dashboard;

Output

Resultant design

I think there is something wrong with my approach. It would be really great if anyone points it out. Thanks.


Solution

  • Remove the width: '44%' in widgets style and replace it with flex: 1. Also, instead of margin between widgets.

    row: {
        flex: 1,
        flexDirection: 'row',
        height:120,
        marginTop: 15,
        marginBottom: 15,
      },
      widgets: {
        backgroundColor: '#fff',
        elevation: 2,
        flex: 1,
        marginLeft: 15,
        marginRight: 15
      }
    

    There is a Expo snack which works within your Expo app: https://snack.expo.io/@vijayst/widgets