prasang7
prasang7

Reputation: 571

React Native - Parent View to wrap the child view

I have a view having text inside it. The component looks like this:

MyComponent = () => {
    return (
        <View style={styles.viewStyle}>
            <Text style={styles.textStyle}>My Text</Text>
        </View>
    );
}

const styles = {
    viewStyle: {
        backgroundColor: '#006699',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
    },
    textStyle: {
        color: '#000000',
        fontSize: 16,
    }
}

When this component gets used, I want my View to have a custom width such that it just wraps my text. Here's the visual clue:

enter image description here

Upvotes: 0

Views: 3027

Answers (1)

Val
Val

Reputation: 22797

It's about the original design of Layout with Flexbox.

You can make it work by either add flexDirection: 'row' to it's parent view (so it will stretch automatically related to <Text /> width),

<View style={{flex: 1, flexDirection: 'row'}}>
  <View style={styles.viewStyle}>
    <Text style={styles.textStyle}>My Text</Text>
  </View>                
</View>

or give width to it directly.

<View style=[{styles.viewStyle}, {width: 50}]>
  <Text style={styles.textStyle}>My Text</Text>
</View>                

Result of option 1:

enter image description here

Upvotes: 1

Related Questions