Layout with Flexbox

Learn how to lay out components in React Native using Flexbox.

Flexbox is a layout method designed to provide consistent design layouts for different screen sizes. It comes with several properties, such as flexDirection, alignItems, and justifyContent. We can use these properties to achieve a suitable layout for our application. The behavior of Flexbox in React Native is similar to its behavior in CSS.

Press + to interact
Layout with Flexbox
Layout with Flexbox

Properties

Let’s review some of the most common properties of Flexbox in React Native.

flex

The flex property defines how our components will fill the available space along the main axis. The space is partitioned based on the flex attribute assigned to each component. The code snippet below shows how to use the flex property of the Flexbox.

Press + to interact
import React from 'react';
import { SafeAreaView, View, StyleSheet } from 'react-native';
const App = () => {
return (
<SafeAreaView style={styles.container}>
<View style={styles.style1} />
<View style={styles.style2} />
<View style={styles.style3} />
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
style1: {
flex: 1,
backgroundColor: 'orange'
},
style2: {
flex: 2,
backgroundColor: 'red'
},
style3: {
flex: 3,
backgroundColor: 'blue'
}
});
export default App;

flexDirection

The flexDirection is used to specify whether the components will be aligned vertically or horizontally. It determines the main axis. The flexDirection property can have these values:

  • column: This is the default value. In column, the child components are aligned from top to bottom.

  • row: The child components are aligned from left to right.

  • column-reverse: The child components are aligned from bottom to top.

  • row-reverse: The child components are aligned from right to left. ...

Access this course and 1400+ top-rated courses and projects.