0
0
React Nativemobile~5 mins

Width, height, and flex in React Native

Choose your learning style9 modes available
Introduction

Width, height, and flex help you control how big or small your app parts look on the screen. They make your app look nice on different devices.

When you want a button to be a certain size on the screen.
When you want a box to fill the whole screen or just part of it.
When you want items to share space evenly or in a custom way.
When you want your app to look good on phones and tablets with different screen sizes.
Syntax
React Native
const styles = StyleSheet.create({
  box: {
    width: 100,       // fixed width in pixels
    height: 50,       // fixed height in pixels
    flex: 1           // flexible size to fill space
  }
});

width and height set fixed sizes in pixels.

flex makes the item grow or shrink to fill available space.

Examples
This box will always be 150 pixels wide and 100 pixels tall.
React Native
const styles = StyleSheet.create({
  box: {
    width: 150,
    height: 100
  }
});
This box will grow to fill all available space in its container.
React Native
const styles = StyleSheet.create({
  box: {
    flex: 1
  }
});
This box will take twice as much space as a sibling with flex: 1.
React Native
const styles = StyleSheet.create({
  box: {
    flex: 2
  }
});
Sample App

This app shows three colored boxes in a row. The first box is fixed size 100x100 pixels. The second and third boxes share the rest of the space. The third box is twice as wide as the second because it has flex 2.

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

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.box1}>
        <Text style={styles.text}>Fixed Size</Text>
      </View>
      <View style={styles.box2}>
        <Text style={styles.text}>Flex 1</Text>
      </View>
      <View style={styles.box3}>
        <Text style={styles.text}>Flex 2</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    padding: 10
  },
  box1: {
    width: 100,
    height: 100,
    backgroundColor: '#f28b82',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 10
  },
  box2: {
    flex: 1,
    backgroundColor: '#fbbc04',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 10
  },
  box3: {
    flex: 2,
    backgroundColor: '#34a853',
    justifyContent: 'center',
    alignItems: 'center'
  },
  text: {
    color: 'white',
    fontWeight: 'bold'
  }
});
OutputSuccess
Important Notes

Use flexDirection to decide if boxes line up in a row or column.

Fixed width and height override flex size.

Flex works best when container has a size (like flex: 1 on container).

Summary

Width and height set fixed sizes in pixels.

Flex lets items grow or shrink to fill space.

Use flex to make your app look good on different screen sizes.