React Native View shrinks to fit content when centered

Viewed 2638

I have a React Native View that I would like to have extend up to but not exceed a given width. Inside this View, I have a Text element that I would like to fill out the full width of its parent. It looks like this: No Alignment Set

However, if I set the parent View to center align with alignSelf: 'center' the view will shrink to fit the text inside the Text view, like so: Center Alignment Set

Why does changing the alignment of a View cause it to change size, and how can I prevent this?

Expected Output: enter image description here

Complete code to replicate this scenario:

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


export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.box}>
        <Text style={styles.paragraph}>Text</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  box: {
    backgroundColor: 'red',
    height: 50,
    maxWidth:200,
    alignSelf: 'center'  // <---REMOVE THIS LINE TO FILL VIEW
  },
  paragraph: {
    textAlign: 'left',
    backgroundColor: 'green',
  },
});

Why adding width will not work

While setting a fixed width value would enforce the maximum size, it would prevent this element from shrinking down below that value. For this reason, specifying width is not a solution. Here is an example situation where the size of the view would extend past the display.

With width:

enter image description here

Expected:

enter image description here

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


export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.box}>
        <Text style={styles.paragraph}>Text</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignContent:'center',//ADD THIS LINE
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  box: {
    backgroundColor: 'red',
    height: 50,
    maxWidth:200,
  },
  paragraph: {
    textAlign: 'left',
    backgroundColor: 'green',
  },
});

expo

Related