Categories
JavaScript Answers React Native Answers

How to set the width of a View to 80% of parent in React Native?

Spread the love

Sometimes, we want to set the width of a View to 80% of parent in React Native.

In this article, we’ll look at how to set the width of a View to 80% of parent in React Native.

How to set the width of a View to 80% of parent in React Native?

To set the width of a View to 80% of parent in React Native, we can set the flexbox and width styles.

For instance, we write:

import * as React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Card } from 'react-native-paper';

const widthProportion = '80%';
const heightProportion = '40%';

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#5A9BD4',
  },
  box: {
    width: widthProportion,
    height: heightProportion,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'orange',
  },
  text: {
    fontSize: 18,
  },
});

const App = () => {
  return (
    <View style={styles.screen}>
      <View style={styles.box}>
        <Text style={styles.text}>hello world</Text>
      </View>
    </View>
  );
};
export default App;

to add the box style that sets the width and height of the box.

We set the width to '80%' to make the box fill 80% of the width of the parent.

Then we set justifyContent and alignItems to 'center' to center align the View box horizontally and vertically respectively.

Conclusion

To set the width of a View to 80% of parent in React Native, we can set the flexbox and width styles.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *