Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align child views to left with even space in React-Native?

I'm trying to create a menu for my application in React-Native which should have multiple icons in the below way enter image description here

The icons should be in the same row and wrapped so that if screen is bigger more icons will be on the same row.

My current code is as follows

import React from 'react';
import { StyleSheet, View } from 'react-native';

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.box}></View>
        <View style={styles.box}></View>
        <View style={styles.box}></View>
        <View style={styles.box}></View>
        <View style={styles.box}></View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'space-evenly',
    flexDirection: 'row',
    flexWrap: 'wrap',
    paddingTop: 40
  },
  box: {
    width: 100,
    height: 100,
    backgroundColor: 'aqua',
    margin: 10,
  }
});

The current output is as below

enter image description here

The children count may change in the future but i need to have spacing on the sides, using flex-start will give the below output which is wrong.i want to have spacing in both sides as well.

enter image description here

How do i align it to left and have the items with even space around as the image above ?

like image 409
Guruparan Giritharan Avatar asked Mar 07 '19 04:03

Guruparan Giritharan


People also ask

How do I align items left in React Native?

left: Used to align the text component to the left-hand side. right: align text to the right-hand side (make sure to add flex: 1). center: It align text component to the center (make sure to add flex: 1). auto: It align text automatically.

How do you align components horizontally in React Native?

To center a component horizontally and vertically in React. js, set its display property to flex and its alignItems and justifyContent properties to center . The components's content will be horizontally and vertically centered.


1 Answers

for Box use Dimensions, Based on screen width divide box width

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'flex-start',
    flexDirection: 'row',
    flexWrap: 'wrap',
    paddingTop: 40
   },
  box: {
    width: (Dimensions.get('window').width / 3) - 20, /* minus some value for adjust the gap between boxes */
    height: 100,
    backgroundColor: 'aqua',
    margin: 10,
  }
});
like image 164
koneri ranjith kumar Avatar answered Sep 25 '22 22:09

koneri ranjith kumar