Sunday, March 24, 2019

React Native Set View Width and Height in Percentage Flex Dimensions

This tutorial explains how to set the width and height of the views in percentage flex dimensions in react native application. Use flex in a component's style to have the component expand and shrink dynamically based on available space. Normally you will use flex: 1, which tells a component to fill all available space, shared evenly amongst other components with the same parent. The larger the flex given, the higher the ratio of space a component will take compared to its siblings.
Flex is used inside the component’s style . Using the Flex, the height and width can expand and fill automatically itself on the available device surface free space.

React Native Set View Width and Height in Percentage Flex Dimensions

React Native Flex Dimensions

Lets see the below example, where we are creating a parent view with flex :1 . Now this tell the application to fill out the whole screen in height and width. Now we would going to create 4 children view inside the root parent view. Using the style now we are going the set all of four children views Flex. This will divide the whole screen according to given flex in width and height.

App.js

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

export default class App extends Component {

  render() {

    return (
      <View style={styles.container}>
        <View style={{ flex: 1, backgroundColor: '#f44336' }} />
        <View style={{ flex: 2, backgroundColor: '#9c27b0' }} />
        <View style={{ flex: 3, backgroundColor: '#009688' }} />
        <View style={{ flex: 3, backgroundColor: '#8bc34a' }} />        
      </View>
    );
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
  },

NOTE : 
A component can only expand to fill available space if its parent has dimensions greater than 0. If a parent does not have either a fixed width and height or flex, the parent will have dimensions of 0 and the flex children will not be visible.

Screenshot :

React Native Set View Width and Height in Percentage Flex Dimensions

This is all about Set View Height Width in Percentage Flex Dimensions in React Native. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment