Flexible grids

Sometimes, you need a screen layout that flows like a grid. For example, what if you have several sections that are the same width and height, but you're not sure how many of these sections will be rendered? The flexbox makes it easy to build a row that flows from left to right until the end of the screen is reached. Then, it automatically continues rendering elements from left to right on the next row.

Here's an example layout in portrait mode:

The beauty of this approach is that you don't need to know in advance how many columns are in a given row. The dimensions of each child determine what will fit in a given row. Let's take a look at the styles used to create this layout:

import { Platform, StyleSheet, StatusBar } from 'react-native';

export default StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
backgroundColor: 'ghostwhite',
alignItems: 'center',
...Platform.select({
ios: { paddingTop: 20 },
android: { paddingTop: StatusBar.currentHeight }
})
},

box: {
height: 100,
width: 100,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'lightgray',
borderWidth: 1,
borderStyle: 'dashed',
borderColor: 'darkslategray',
margin: 10
},

boxText: {
color: 'darkslategray',
fontWeight: 'bold'
}
});

Here's the App component that renders each section:

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

import styles from './styles';
import Box from './Box';

// An array of 10 numbers, representing the grid
// sections to render.
const boxes = new Array(10).fill(null).map((v, i) => i + 1);

export default () => (
<View style={styles.container}>
<StatusBar hidden={false} />
{/* Renders 10 "<Box>" sections */}
{boxes.map(i => <Box key={i}>#{i}</Box>)}
</View>
);

Lastly, let's make sure that the landscape orientation works with this layout:

You might have noticed that there's some superfluous space on the right side. Remember, these sections are only visible in this book because we want them to be visible. In a real app, they're just grouping other React Native components. However, if the space to the right of the screen becomes an issue, play around with the margin and the width of the child components.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.214.215