Open In App

How to use Flexbox in React Native ?

Flexbox is used to provide consistency to a layout. It is used to make the layout adaptive to the screen size of the device it is running on. Using flexbox design you can specify that a certain element of layout will span to this fraction of the available space.

In React Native, Flexbox is the same as it is for basic CSS. The only difference being in default values.



Now let’s start with the implementation:

Project Structure: It will look like this.

Project Structure

Flex property: Flex property will define how the components in your layout are going to span over the available space along your main axis which by default is a column. Space will be divided in the ratio of each element’s flex property.

Example: Write down the following code in the App.js file.




import React from 'react';
import {View } from 'react-native';
  
export default function App() {
  return (
    <View style={{
      flex: 1
    }}>
        <View style={{ flex: 4, backgroundColor: "white" }} />
        <View style={{ flex: 1, backgroundColor: "black" }} />
        <View style={{ flex: 7, backgroundColor: "green" }} />
      </View>
  );
}

Start the server by using the following command.

npm run android

Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again.  

 

Output

Flex Direction Property: The flexDirection property controls the direction in which the children of a node are laid out, that is, the main axis. There are four types of flexDirection given below:

Example: Write down the following code in the App.js file.




import React from 'react';
import {View } from 'react-native';
  
export default function App() {
  return (
    <View style={{
      flex: 1,
      flexDirection: "row",
    }}>
        <View style={{ flex: 4, backgroundColor: "white" }} />
        <View style={{ flex: 1, backgroundColor: "black" }} />
        <View style={{ flex: 7, backgroundColor: "green" }} />
      </View>
  );
}

Start the server by using the following command.

npm run android

Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again.  

Output

Reference: https://reactnative.dev/docs/flexbox


Article Tags :