The struggle is real

Understanding Flexbox in React Native

Mastering these simple Flexbox recipes will make you a React Native UI master in no time

Getting Started

Lets start with a simple example. A container component with three components.

//Our views<View style={styles.container}>
<View style={styles.viewStyleOne}>
<Text style={styles.textStyle}> 1 </Text>
</View>
<View style={styles.viewStyleTwo}>
<Text style={styles.textStyle}> 2 </Text>
</View>
<View style={styles.viewStyleThree}>
<Text style={styles.textStyle}> 3 </Text>
</View>
</View>//Styleslet styles = StyleSheet.create({
container: { backgroundColor:'#4286f4'},
viewStyleOne: {
width:40,
height:40,
justifyContent: 'center',
alignItems:'center',
backgroundColor:'#b642f4'
},
textStyle:{
textAlign:'center'
}
})

Which renders as so:

Initial View

Styling the Container

Now we add flex:1 to the container:

container: { 
backgroundColor:'#4286f4',
flex: 1
}

This makes container fill its parent, i.e. whole screen.

flex : 1

Now we add:

container: { 
backgroundColor:'#4286f4',
flex: 1,
flexDirection:'row'
}

Each view’s is set to colum by default but setting it to ‘row’ will change the orientation of the items in the container.

flexDirection set to ‘row’

Now we can control the orientation of the content using .
Now lets add and :

container:{ 
backgroundColor:'#4286f4',
flex: 1,
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems:'flex-start'
}
justifyContent: ‘flex-end’

Similarly for:

container: { 
backgroundColor:'#4286f4',
flex: 1,
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems:'flex-end'
}

Views will render like:

alignItems:’flex-end’
  • determines the primary axis as ‘row’ or ‘column’.
  • determines distribution of children along primary axis.
  • determines the alignment of children along the secondary axis.

To set items to center :

justifyContent: 'center',
alignItems:'center'
Items to center

supports , , , , and .

For :

space-around

and :

supports: , , , and .

Overriding the Container Style

If we need an item to override it’s defined as defined by the container we could use style the items individually.

overrides and supports these options , , , , and .

If we tell an item to align itself to

alignSelf: 'flex-start' 

It would end up like this:

telling the item to align at flex start

controls how much the item will grow relative to the rest of the flexible items inside the same container.

flexGrow: 1

Would render as:

flexGrow

controls the item size with percent. For eg:

flexBasis:50 //firstView style
flexBasis:20 //secondView style
flexBasis:30 //ThirdView style
flexBasis

Thanks for Reading!

These are the basic use of flex for React View components. I will update as I learn more. Thanks for reading and feel free to leave questions in the comments!

React Native Coach

Bringing you the best React Native, GraphQL, Redux, and…