Home > Software design >  React Native flex children gone when declaring flex property
React Native flex children gone when declaring flex property

Time:09-16

My component is extremely simple, I have a <View> component with a flex:1 property.

I have another View inside of that parent View with a property of flex: .5, from my understanding - it should take up 50% of the parent View's height. But it doesn't take up anything, it's gone as if there is no element there. height: "50%" works though.

CodePudding user response:

because of the other view with flex: 1 take the entire space of parent, flex: 1 means width: 100% or height: 100% of the parent (depends on the flex direction).

Change to flex: .5 for both Views and you will see them in the half and half of parent.

CodePudding user response:

If your code is like the following, it should be working.

<View style={{flex: 1, backgroundColor: 'blue'}}>
  <View style={{flex: .5, backgroundColor: 'red'}} />
</View>

Just be aware the component above will affected by its parent View as well. Please check all the flex in parent views. Also, it is good to provide any of the code in the question to make it easier for debugging.

CodePudding user response:

As per your program you have used only View component inside another View component. also you have added style {flex:1} to parent view and {flex: 0.5} style to child.

Problem : your problem is child view is not taking 50% of the parent using {flex: 0.5}.

Solution : if you want to access 50% of the parent using {flex: 0.5} then you have to add any component like Text component inside of child View etc..

ex:

    /**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

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

const App = () => {

  return (
    <View style={{ flex: 1, flexDirection:'row' }}>
      <View style={{ flex: 0.5, backgroundColor: 'red' }}>
        <Text>{"Hello"}</Text>
      </View>
    </View>
  );
};


export default App;
  • Related