0

I want to create a 3x4 grid layout of squares that is device independent. The container <View> for these squares has an unknown width/height. I want the squares to grow to fill the available container.

Code for container:

squaresContainer: {
    alignSelf: 'center',
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    flex: 1,
    marginHorizontal: 15
}

And the 'squares' (which are currently not squares), using 33% flexBasis to get the 3 columns. There will always be 12 squares total so the four rows should always happen.

square: {
    alignItems: 'center',
    justifyContent: 'center',
    flexGrow: 1,
    flexShrink: 0,
    flexBasis: '33%'
}
pfinferno
  • 1,779
  • 3
  • 34
  • 62

1 Answers1

0

Actually, the flex-box takes care of only one axis, so you can't use it to control both rows and columns. But you can achieve what you described above by wrapping every 4 views in a parent view. for example:

import React, { useState } from "react";
import { View } from "react-native";

const Square = ({ backgroundColor }) => {
  const [height, setHeight] = useState(0);
  return (
    <View
      onLayout={(e) => setHeight(e.nativeEvent.layout.width)}
      style={{ flex: 1, height, backgroundColor }}
    />
  );
};

export default function App() {
  return (
    <View style={{ flexDirection: "column" }}>
      <View style={{ flex: 1, flexDirection: "row" }}>
        <Square backgroundColor="red" />
        <Square backgroundColor="pink" />
        <Square backgroundColor="orange" />
        <Square backgroundColor="green" />
      </View>
      <View style={{ flex: 1, flexDirection: "row" }}>
        <Square backgroundColor="lightgreen" />
        <Square backgroundColor="yellow" />
        <Square backgroundColor="blue" />
        <Square backgroundColor="lightblue" />
      </View>
      <View style={{ flex: 1, flexDirection: "row" }}>
        <Square backgroundColor="skyblue" />
        <Square backgroundColor="brown" />
        <Square backgroundColor="gray" />
        <Square backgroundColor="red" />
      </View>
    </View>
  );
}

Or by using an external library to support the grid:

Yaman KATBY
  • 1,814
  • 10
  • 24
  • Will look into those libraries. But for your example, how would those be squares? If I want the height/width to be responsive? – pfinferno Jan 21 '22 at 11:37
  • Actually, you can see the result of my example here: https://snack.expo.dev/@yamankatby/vengeful-chocolate – Yaman KATBY Jan 21 '22 at 11:38
  • @pfinferno Now the height will match the width try it: https://snack.expo.dev/@yamankatby/vengeful-chocolate – Yaman KATBY Jan 21 '22 at 11:45