Make view 80% width of parent in React Native

Mark Amery picture Mark Amery · Nov 26, 2015 · Viewed 165.4k times · Source

I'm creating a form in React Native and would like to make my TextInputs 80% of the screen width.

With HTML and ordinary CSS, this would be straightforward:

input {
    display: block;
    width: 80%;
    margin: auto;
}

Except that React Native doesn't support the display property, percentage widths, or auto margins.

So what should I do instead? There's some discussion of this problem in React Native's issue tracker, but the proposed solutions seem like nasty hacks.

Answer

GollyJer picture GollyJer · Jul 25, 2017

As of React Native 0.42 height: and width: accept percentages.

Use width: 80% in your stylesheets and it just works.

  • Screenshot

  • Live Example
    Child Width/Height as Proportion of Parent

  • Code

    import React from 'react';
    import { Text, View, StyleSheet } from 'react-native';
    
    const width_proportion = '80%';
    const height_proportion = '40%';
    
    const styles = StyleSheet.create({
      screen: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#5A9BD4',
      },
      box: {
        width: width_proportion,
        height: height_proportion,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#B8D2EC',
      },
      text: {
        fontSize: 18,
      },
    });
    
    export default () => (
      <View style={styles.screen}>
        <View style={styles.box}>
          <Text style={styles.text}>
            {width_proportion} of width{'\n'}
            {height_proportion} of height
          </Text>
        </View>
      </View>
    );