Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native View shrinks to fit content when centered

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

like image 325
Software2 Avatar asked Jul 21 '26 21:07

Software2


1 Answers

The trick is to add both maxWidth: 200 and width: "100%". Then the width will expand to be as wide as possible, but remain constrained to a maximum of 200.

  box: {
    backgroundColor: 'red',
    height: 50,
    maxWidth:200,
    width: '100%',
    alignSelf: 'center'  // <---REMOVE THIS LINE TO FILL VIEW
  },
like image 102
chmac Avatar answered Jul 23 '26 15:07

chmac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!