Horizontally centering left-justified text

Code: https://dpaste.org/doOc/slim

Screenshot:

I would like to center the left-justified text (named “subheader” in the code linked above). How can I do this? The large text (named “header”) is centering properly with flex, but the subheader is not.

I am ready to reproduce your problem.

What is your code?

import * as React from "react";
import { View,
         Text } from "react-native";
​
const styles = StyleSheet.create({
    content: {
        flexDirection: "column",
        alignItems: "center",
        paddingTop: 35
    },
    header: {
        fontFamily: "sans-serif",
        fontWeight: "bold",
        fontSize: 34
    },
    subheader: {
        fontFamily: "sans-serif",
        fontSize: 22,
        textAlign: "left"
    }
});
​
const MyView = () => (
    <View style={styles.content}>
        <View>
            <Text style={styles.header}>Welcome</Text>
        </View>
        <View>
            <Text style={styles.subheader}>This text is designed to wrap as an example.</Text>
        </View>
    </View>
);
​
export default MyView;

Hi

If you add a border around the subheader you will see that it is actually centered (or it’s taking up the whole width of your screen). So the problem is not the centering, but rather that the <Text> is not fitting tightly around its contents.

e.g.:

  subheader: {
    fontFamily: 'sans-serif',
    fontSize: 22,
    textAlign: 'left',
    width: 250,
    borderWidth: 1,
    borderColor: 'red',
  },

and:

    <View style={{ borderWidth: 1, borderColor: 'green', padding: 1 }}>
      <Text style={styles.subheader}>
        This text is designed to wrap as an example.
      </Text>
    </View>

So basically it seems you want the subheader to expand to as wide as it can be, but of course it should wrap if the screen is not wide enough to show the full subheader. But, the <Text> should only be as wide as needed to fit the wrapped text and should not expand to the width of the whole screen. And of course you don’t want to specify a width yourself.

Off hand I don’t know how to do that, but I hope the above at least explains the problem.