Difference between Flexbox in React Native and Flexbox in Web Dev

Difference between Flexbox in React Native and Flexbox in Web Dev

To understand the difference first we need to know what one achieves by using flexbox at all.

We use flexbox in both of these applications, just to align the items on the screen.

-Flexbox in Web Development

To understand this let's look at the following code in web dev:

Here the parent element has the display : flex property, which makes it a flexbox. Then we see two more properties:

  1. justify-content : Used to align the child items horizontally in the flexbox, i.e. along the main axis.

  2. align-items : Used to align the child items vertically in the flexbox, i.e. along the cross axis.

-Flexbox in React Native:

Here, the flexbox axes are interchanged, i.e. the elements are stacked from top-to-bottom, unlike bottom-to-top in web development.

import React from 'react';

import {View, Text, StyleSheet, useColorScheme} from 'react-native';

const AppPro = (): JSX.Element => {
  const isDarkMode = useColorScheme() === 'dark';
  return (
    <View style={styles.container}>
      <Text style={isDarkMode ? styles.whiteText : styles.darkText}>
        Hello World!
      </Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  whiteText : {
    color: '#fff', 
    fontSize: 30,
  },
  darkText : {
    color: '#000',
    fontSize: 30,
  }
});

export default AppPro;

In the code above, we have the View element using styles.container as its style. Observe that "container" has three properties inside the styles object.

  1. flex : turns the container into a flexbox

  2. justify-content : Used to align the child items vertically in the flexbox, i.e. along the main axis.

  3. align-items : Used to align the child items horizontally in the flexbox, i.e. along the cross axis.


Summary

justify-content manages the alignment of elements along the main axis,
while the align-items manages the alignment of elements along the cross axis in both these cases.

It is just that the axes are interchanged with each other i.e. cross axis in web dev is main axis in react native and vice-versa.